且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从数组列表中提取唯一值

更新时间:2022-06-10 00:08:33

代码:

    int[] input = new int[]{0, 0, 0, 0, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 5, 8, 8, 10, 10, 2, 2, 2, 3, 3, 7, 7};
    int current = input[0];
    boolean found = false;

    for (int i = 1; i < input.length; i++) {
        if (current == input[i] && !found) {
            found = true;
        } else if (current != input[i]) {
            System.out.print(" " + current);
            current = input[i];
            found = false;
        }
    }
    System.out.print(" " + current);

输出:

0 2 3 5 8 10 2 3 

说明:

您通过设置数组的第一个值来设置电流 在循环内部,如果当前值等于每个元素 并且标志fount为false,表示未看到重复项,并且 您现在已经看到了,所以找到变量的标志有 设置为true,表示已找到重复的内容或看到重复的内容 没有.

you set current with first value of array after that you go through the loop.Inside the loop, if the current value equal to each elements and flag fount is false which mean duplicate have been not seen and you it has been seen right now, so flag which is found variable has been set to true which shows duplicate has been found or seen an do nothing.

对于else部分,如果数组的元素不等于当前 变量意味着没有重复,而正确的当前变量表明 包含在控制台上以前见过的重复项.更新 具有新重复项的可变电流并将设置标志设置为false 节目还没看过新看过的重复.继续这样做,就在最后 遍历循环后,复制变量.

For the else part, if the element of array not equal to current variable means there is not duplicate, and right current variable that contains the before seen duplicate at the console. Update the variable current with new duplicate and set flag found to false which shows have not seen new seen duplicate. Keep doing this and right last duplicate variable when you are done traversing the loop.