leetCode Numeric problem records that occur only once

Questions are as follows

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

illustrate:
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

 

My answer is as follows:

     Arrays.sort(nums);

        if (nums.length == 3){
            if(nums[0] != nums[1]){
                return nums[0];
            }
            if(nums[1] != nums[2]){
                return nums[nums.length-1];
            }
        }

        for(int i = 1;i<nums.length-2;i++){

            if(nums[0] != nums[1]){
                return nums[0];
            }
            if(nums[nums.length-2] != nums[nums.length-1] && nums[nums.length-2] == nums[nums.length-3]){
                return nums[nums.length-1];
            }

            if(nums[i-1] != nums[i] && nums[i] != nums[i+1]){
                return nums[i];
            }
        }
        return nums[0];

Idea: Sort the array and then compare the element at position i with the elements before and after it. If they are not equal, it means that he is the only one that appears, and then deal with the situation where the unequal data appears at the head and tail of the array, and finally deal with it. When the length of the array is 3 and 1, in these two cases, the array will be out of bounds according to the above logic.

 

The most efficient solution is given:

        int xor = 0;
        for (int i = 0; i < nums.length; i++ ) {
            xor ^= nums[i];
        }
        return xor;

Among them, ^ is the exclusive OR operator, which converts the number to binary and performs bitwise operations. For example, the binary representation of 15 is 1111, and the binary representation of 2 is 0010. Then the result of 15^2 is 1101 and returned The value is 13.

The effect of a^=b is equivalent to a=a^b. The element obtained after performing two consecutive XOR operations on one element with another element is still itself. When the XOR operation is performed on the entire array, the final xor obtained is the only one sought.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325754293&siteId=291194637