简体   繁体   English

使用for循环和。搜索值

[英]Searching a value using for-loop and

The question is this: 问题是:

Given a non-empty array of integers, every element appears twice except for one. 给定一个非空的整数数组,除了一个元素外,每个元素都会出现两次。 Find that single one. 找一个单一的。

Input: [4,1,2,1,2] 输入:[4,1,2,1,2]
Output: 4 产量:4

my code is: 我的代码是:

public static int singleNumber(int[] nums) {
     int answer = 0;
        for (int i =0; i<nums.length-1; i++) {
            for(int j = i+1; j<nums.length; j++) {
                if(nums[i] != nums[j]) {
                 answer = nums[i];      //this should be where I am wrong.
                }
            }
        }
        return answer;
    }

I know that the output was 4 and then now it will be changed to 1. I'm trying to figure out how not to change the found value once found. 我知道输出是4然后现在它将被改为1.我试图找出如何在找到后不改变找到的值。

The logic is wrong - your inner loop finds every number that isn't the only number in the array. 逻辑是错误的 - 你的内部循环找到的每个数字都不是数组中唯一的数字。

I'd maintain a Set to track the numbers I've encountered. 我会保留一个Set来跟踪我遇到的数字。 The first time you encounter a number, you add it to the Set . 第一次遇到数字时,将其添加到Set The second time you encounter it, you remove it from the Set . 第二次遇到它时,将其从Set删除。 Once you're done going over the array, you'd have a Set with a single element, which is your answer: 一旦你完成了数组,你就会得到一个包含单个元素的Set ,这是你的答案:

public static int singleNumber(int[] nums) {
    Set<Integer> unique = new HashSet<>();
    for (int num : nums) {
        // add returns true if num is indeed new to unique
        if (!unique.add(num)) {
            unique.remove(num);
        }
    }

    return unique.iterator().next();
}

For this problem, i would to bitwise XOR of the numbers. 对于这个问题,我想对数字进行按位异或。 The numbers that are equal will cancel one another and only single integer will be the final value. 相等的数字将相互抵消,只有一个整数将是最终值。

public static int singleNumber(int[] nums) {
     int answer = 0;
        for (int i =0; i<nums.length; i++) {
           answer = answer ^ nums[i];
        }
        return answer;
 }

below changes to your method will give you the expected answer 以下对您的方法的更改将给您预期的答案

public static int singleNumber(int[] nums) {

    int temp = 0;
    int answer = 0;

    for (int i = 0; i < nums.length; i++) {
        boolean flag = true;
        temp = nums[i];
        for (int j = 0; j < nums.length; j++) {
            if (temp == nums[j]) {
                if (i != j) {// if a match found then the loop will terminate
                    flag = false;
                    break;
                }
            }

        }
        if (flag == true) {
            answer = temp;
        }
    }
    return answer;
}

Here is another solution using Collectors.groupingBy from Java 8 : 以下是使用Java 8中的Collectors.groupingBy另一种解决方案:

public static int singleNumber(int[] nums) {
    return Arrays.stream(nums).boxed()
            .collect(Collectors.groupingBy(a -> a, Collectors.counting()))
            .entrySet().stream().filter(e -> e.getValue() == 1).findFirst().get().getKey();
}

the idea is : 这个想法是:

  • group by number of occurence 按发生次数分组
  • then find the one which is repeated just one time 然后找到一次重复的那个

Note I assume that your array contain at least one element, else you can check the length before you search then throw an exception like this : 注意我假设你的数组至少包含一个元素,否则你可以在搜索之前检查长度,然后像这样抛出一个异常:

public static int singleNumber(int[] nums) throws IllegalArgumentException{
    if(nums.length == 0){
        throw new IllegalArgumentException("empty array");
    }
    return Arrays.stream(nums).boxed()
            .collect(Collectors.groupingBy(a -> a, Collectors.counting()))
            .entrySet().stream().filter(e -> e.getValue() == 1).findFirst().get().getKey();
}

More deeper, If you want to avoid the situation where there are multiple number repeated just one time you can use : 更深入,如果你想避免只有一次重复多次的情况,你可以使用:

public static int singleNumber(int[] nums) throws IllegalArgumentException {
    if (nums.length == 0) {
        throw new IllegalArgumentException("empty array");
    }
    Map<Integer, Long> grouping = Arrays.stream(nums).boxed()
            .collect(Collectors.groupingBy(a -> a, Collectors.counting()));
    if (grouping.values().stream().filter(c -> c == 1).count() > 1) {
        throw new IllegalArgumentException("more than one element is repeated one time");
    }

    return grouping.entrySet().stream()
            .filter(e -> e.getValue() == 1).findFirst().get().getKey();
}

Here is a solution which uses ArrayList.indexOf and ArrayList.lastIndexOf. 这是一个使用ArrayList.indexOf和ArrayList.lastIndexOf的解决方案。 If they are same, you have your answer. 如果它们相同,那么你有答案。

public static int singleNumber(int[] nums) {
    int answer = 0;
    //ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(nums));
    ArrayList al = new ArrayList();
    for (int i =0; i < nums.length; i++) {
        al.add(nums[i]);
    }

    for (int i =0; i < nums.length; i++) {
        int test = nums[i];
        if(al.indexOf(test) == al.lastIndexOf(test)){
            answer = nums[i];
        }
    }
    return answer;
 }

Try this: 尝试这个:

    int[] nums = new int[] {4,2,1,2,1};
         int answer = 0;
            for (int i =0; i<nums.length-1; i++) {
                int times = 0;
                int target = nums[i];
                for(int j : nums) {
                    if(j == target) {
                        times++;
                        if(times == 2) {
                            break;
                        }
                    }
                }
                if(times == 1) {
                    answer = target;
                    break;
                }
            }
            System.out.println(answer);

you have to go into every number and count how meny are in the array if there is only 1 you instantly stop the loop end set the answer 你必须进入每个数字并计算数组中的meny如果只有1你立即停止循环结束设置答案

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

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