Leetcode single number系列

1代

Given a non-empty 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?

Example 1:

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

Example 2:

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

给定一个非空整数序列,序列中所有数值都是两个,除了一个数,请找出这个数

解法:相同的数异或为0,所以当所有数异或之后,就可以找到单独的那个数

代码:

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for(int i : nums) {
           result ^= i;
        }
        return result;
    }
}

 

2代

Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:

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

Example 1:

Input: [2,2,3,2]
Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99

这一次数字序列中相同的数值都是3个,除了有一个单独的

解法:

我们可以进行移位操作,计算每个位上的一的个数是否为3的倍数,如果不是,说明该位掺进了单独的那个数,最后计算拼加即可。

代码:

class Solution {
    public int singleNumber(int[] nums) {
        int []bits=new int[32];
        int re=0;
        for(int i=0;i<32;i++){
            for(int j=0;j<nums.length;j++){
                bits[i]+=(nums[j]>>i)&1;
            }
        }
        
        for(int i=0;i<32;i++){
            int d=bits[i]%3==0?0:1;
            re+=d<<i;
        }
        return re;
    }
}

3代:

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.

Example:

Input:  [1,2,1,3,2,5]
Output: [3,5]

给出一串整数序列,每个数值都出现两次,只有两个数值只出现一次,找出这两个数值

解法:

将所有数值异或,相同的值异或为0,所以异或的结果为 两个不同数值异或的结果,例如给定的示例,异或的最终结果为6(0110),且 6^3=5,6^5=3;

现在就变为要如何将6分解为 3和5

我们可以根据结果中的1来判断,最终结果某位出现1,说明这两个不相同的数字在该位一个为0,一个为1,我们以此来进行区分。(区分的方法是找出结果中某位1,并提取,之后让序列每个数值与之相与,结果为0的为一批,结果为1的为一批,每批之间再互相异或,就能知道两个单独的数了)

代码:

class Solution {
    public int[] singleNumber(int[] nums) {
                // go through the array and XOR every element, for example, result = 6 (3^5)
                int result = nums[0];
                for(int i = 1; i < nums.length; i++){
                    result ^= nums[i];
                }
                // notice that 6^5 = 3, 6^3 = 5
                // now how to find 3 and 5 from 6
                int[] r = new int[2];
                // find the lowest bit of the result
                // let's say 6 (0110), -6 = 1010  0110 & 1010 = 0010
                int lowbit = result & -result;
                // since this bit from the result is 1, we can be sure that 
                // a & lowbit and b & lowbit have different result
                for(int n : nums){
                    if((n & lowbit) == 0) r[0] ^= n;
                    else r[1] ^=n;
                }
                return r;
    }
}

猜你喜欢

转载自blog.csdn.net/Lin_QC/article/details/92980963