[Rookie Training] LC numbers that only appear once

Title description:

Given an array of non-empty integers, each element appears twice except for one element. Find the element that appears only once.

Explanation:
Your algorithm should have linear time complexity. Can you do it without using extra space?

Example 1:
Input: [2,2,1]
Output: 1

Example 2:
Input: [4,1,2,1,2]
Output: 4

Author: stay button (LeetCode)
link: https: //leetcode-cn.com/leetbook/read/top-interview-questions/xm0u83/
Source: stay button (LeetCode)
copyright reserved by the authors. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Problem-solving ideas:

Method 1:
Use the XOR operation to XOR any number a with itself, and the result will be 0. Any number a and 0 are XORed, the result is a. According to the requirements of the title, in the given array nums, there must be only one number that appears once, and the remaining numbers appear twice, so we XOR all the elements in the array, and the final result is the one that appears once. number. The time complexity is O(n).

Method 2:
Use the set Set, traverse one side of the nums array, if the current element does not exist in the set, add it to the set, if it exists, delete it from the set, so that after the loop, there is only one element in the set , This element is the number that appears only once in the array nums. The time complexity is O(n).

Code:

public class LC1 {
    
    
    //方法一:使用异或操作,任何数和自己异或都为0。任何数a和0异或,结果都为a。
    public int singleNumber(int[] nums) {
    
    
        int ans = nums[0];
        for (int i = 1 ; i < nums.length; i++){
    
    
            ans ^= nums[i];
        }
        return ans;
    }
    //使用Set做
    public int singleNumber1(int[] nums){
    
    
        Set<Integer> set = new HashSet<>();
        boolean flag = false;
        for (int i = 0; i < nums.length; i++){
    
    
            //如果set中没有则将其添加到set中
            if(set.contains(nums[i]) == false){
    
    
                set.add(nums[i]);
            }
            //若set中有,则将其从set中删除
            else {
    
    
                set.remove(nums[i]);
            }
        }
        int ans = 0;
        //根据题意最后set中肯定只存在一个元素,这个元素就是仅出现一次的数
        for (Integer integer : set){
    
    
            ans = integer;
        }
        return ans;
    }

    public static void main(String[] args) {
    
    
        LC1 obj = new LC1();
        int[] nums = new int[]{
    
    3,1,2,1,2};
        System.out.println(obj.singleNumber1(nums));
    }
}

Guess you like

Origin blog.csdn.net/Puppet__/article/details/115246213