剑指Offer 56 I II

170 阅读2分钟

这是我参与8月更文挑战的第28天,活动详情查看:8月更文挑战

剑指 Offer 56 - I. 数组中数字出现的次数

题目

一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。

示例 1:

输入:nums = [4,1,4,6]
输出:[1,6][6,1]

示例 2:

输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10][10,2]

限制:

  • 2 <= nums.length <= 10000

方法一

位运算:

  • 找出两个只出现一次的数的数位上不相等的位,根据这个将两个只出现一次的数分开
  • 分成两个集合后,两个集合中都只有一个数出现过一次,其余的数都出现两次
  • 利用异或运算,将只出现过一次数的分开
class Solution {
    public int[] singleNumbers(int[] nums) {
​
        int bit = 0;
        for (int i = 0; i < 32; i ++ ) {
            int cnt = 0;
            for (int x : nums)
                if (((x >> i) & 1) == 1)
                    cnt ++;
​
            if ((cnt & 1) == 1) {
                bit = i;
                break;
            }
        }
​
        List<Integer> a1 = new ArrayList<>(), a2 = new ArrayList<>();
        for (int x : nums) 
            if (((x >> bit) & 1) == 0) a1.add(x);
            else a2.add(x);
        
​
        int[] res = new int[2];
        for (int x : a1)
            res[0] ^= x;
        for (int x : a2)
            res[1] ^= x;
        
        return res;
    }
}

时间复杂度: O(n)

空间复杂度: O(1)

剑指 Offer 56 - II. 数组中数字出现的次数 II

题目

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。

示例 1:

输入:nums = [3,4,3,3]
输出:4

示例 2:

输入:nums = [9,1,7,9,7,9,7]
输出:1

限制:

  • 1 <= nums.length <= 10000
  • 1 <= nums[i] < 2^31

方法一

位运算:

  • 利用位运算找出指出现一次的数与其他数不同的位数
  • 根据这个位数去判断,该数是否出现了一次
class Solution {
    public int singleNumber(int[] nums) {
        int bit = 0;
        for (int i = 0; i < 32; i ++ ) {
            int cnt = 0;
            for (int x : nums)
                if (((x >> i) & 1) == 1)
                    cnt ++;
​
            if (cnt % 3 == 1) {
                bit = i;
                break;
            }
        }
​
        for (int x : nums) {
            if (((x >> bit) & 1) == 1) {
                int cnt = 0;
                for (int y : nums) 
                    if (y == x)
                        cnt ++;
                if (cnt == 1) return x;
            }
        }
        return 0;
    }
}

方法二

位运算:方法一中,若出现三次的数该数位也为1,则仍然需要计算出现的次数,时间复杂度略高

方法二利用空间来换取时间,记录下每一位%3等于1的数位,最后左移相加即可恢复成只出现一次的数

class Solution {
    public int singleNumber(int[] nums) {
        int[] note = new int[32];
        for (int i = 0; i < 32; i ++ ) {
            int cnt = 0;
            for (int x : nums)
                if (((x >> i) & 1) == 1)
                    cnt ++;
            if (cnt % 3 == 1)
                note[i] = 1;
        }
​
        int res = 0;
        for (int i = 0; i < 32; i ++ )
            if (note[i] == 1)
                res += (1 << i);
        return res;
    }
}