简体   繁体   English

识别数组中的重复数字

[英]Identifying repeating numbers in a array

在此输入图像描述

I am dealing with the following problem. 我正在处理以下问题。 I am not looking for anyone to provide me a solution i am looking for some guidance to solving this problem. 我不是在寻找任何人为我提供解决方案我正在寻找解决这个问题的一些指导。 Here is what i have come up with so far. 这是我到目前为止所提出的。

I have basically tried to first put a ( around values that repeat. However i am getting a out of bounds error. I would really appreciate it if someone can push me towards the right path for coding a small algorithm that would handle this problem. 我基本上试图先放一个(围绕重复的值。但是我得到一个越界错误。如果有人可以推动我走向正确的路径来编写一个可以处理这个问题的小算法,我真的很感激。

My code (in progress) 我的代码(正在进行中)

import java.util.Random;

public class Test {

    public static void main(String[] args) {

        int[] values = { 1, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 6,
                3, 1 };

        boolean inRun = false;

        for (int i = 0; i < values.length; i++) {

            if (values[i] == values[i + 1] && values[i + 1] < values.length) {
                System.out.print("(");

            }

            System.out.print(values[i]);

        }

    }

}

Your error is here, 你的错误在这里,

if (values[i] == values[i + 1] && values[i + 1] < values.length) {

Because i + 1 isn't being tested for less then, or in the correct order - 因为i + 1测试时间不足或者顺序不正确 -

if (i + 1 < values.length && values[i] == values[i + 1]) {

Or you could use, 或者你可以使用,

for (int i = 0; i < values.length - 1; i++) { // the length of values - 1 so we can
                                              // get the next value.

You need to iterate to all the array and if it found a pair then you iterate it again in a while loop until it find the non pair. 你需要迭代到所有数组,如果它找到了一对,那么你在while循环中再次迭代它,直到它找到非对。

sample: 样品:

 int[] values = { 1, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 6, 3, 1 };

 boolean inRun = false;

 for (int i = 0; i < values.length; i++) {

     if (i + 1 < values.length && values[i] == values[i + 1] )
     {
         System.out.print("(");
         while (i + 1 < values.length && values[i] == values[i + 1] )
         {
             System.out.print(values[i++]);
         }
         System.out.print(values[i++]);
         System.out.print(")");
     }
     System.out.print(values[i]);

 }

result: 结果:

12(55)31243(2222)36(55)631

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM