LeetCode 260. Single Number III

Upgraded version:

 

260. Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

 

Analysis: Different from the paired occurrence of the previous two articles to find a single number, this question needs to find two separate numbers, and there is a pit here: if the paired numbers appear, the subtraction is equal to 0, which is no problem; But the subtraction of two numbers that are not equal to 0 must be the two separate numbers you are looking for?

 

The answer is definitely not, because these two numbers that appear alone can appear at the head, tail or middle of the sorting. Simply subtracting them with a step size of 2 will only find one, but the next step size will be messed up.

Solution: 1. Sort;

                  2. If the subtraction of two numbers is equal to 0, the step size is +2

                  3. If the subtraction of the two numbers is not equal to 0, the step size is +1, and the first number is recorded, that is, the first lonely number

                  4. If there is a number remaining at the end, it is the second lonely number.

                  5. Return the result

 

public class Solution {
    public int[] singleNumber(int[] nums) {
        Arrays.sort(nums);
        
        List<Integer> result = new ArrayList<Integer>();
        int index = 0;
        while(index < nums.length - 1) {
            if (nums[index] - nums[index + 1] == 0) {
                index += 2;
            } else {
                result.add(nums[index]);
                index += 1;
            }
        }
        if (index < nums.length) { // 收尾
            result.add(nums[index]);
        }
        
        Integer[] ret = (Integer[])result.toArray(new Integer[0]);
        
        return new int [] {ret [0] .intValue (), ret [1] .intValue ()};
    }
}

 

Guess you like

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