LeetCode 136. Single Number

From today onwards, stick to an algorithm question every day, and post it to your blog when you have time, stick to it! ! ! To make future interviews easier.

 

Let's start with a simple one:

136. Single Number

 

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

 

Analysis: The problem is very simple, give an integer array, one of the numbers appears once, and the others appear in pairs. Find the number that appears alone.

          The title requires two points: 1. Linear time complexity; 2. Do not use additional storage space.

          It is easy to think that the subtraction of pairs of numbers is equal to 0, so as long as the pairs are subtracted, the remaining numbers are the numbers that appear alone.

          Simplest idea I can think of:

          1. Sort the array from large to small, from small to large;

          2. Set the step size to 2, subtract them from each other, if equal to 0, adjust the step size, otherwise find the number that appears alone;

          3. Ending: If the number that appears alone appears in the last one, return directly.

 

code show as below:

public class Solution {
    public int singleNumber(int[] nums) {
        Arrays.sort(nums);
        
        int index = 0;
        while (index < nums.length - 1) {
            if (nums[index] - nums[index + 1] == 0) {
                index = index + 2;
            } else {
                return nums[index];
            }
        }
        
        return nums[index];
    }
}

 

Sort directly using Arrays.sort, if you have other better ideas, welcome to make a brick, thank you!

Guess you like

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