剑指offer56-Ⅱ 数组中出现的次数Ⅱ【数学】

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

题目描述

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

示例 1:

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

示例 2:

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

限制:

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

解题思路

方法一:数学-状态机

数学方法 00->01->10->00;

代码实现

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int singleNumber(int[] nums) {
// two one
int ones = 0, twos = 0;
for(int num : nums){
ones = ones ^ num & ~twos;
twos = twos ^ num & ~ones;
}
return ones;
}
}

复杂度分析

时间复杂度:O(n)

空间复杂度:O(1)

资料

剑指offer56-Ⅱ 数组中出现的次数Ⅱ【数学】

http://example.com/2021/06/03/剑指offer56-Ⅱ-数组中出现的次数Ⅱ/

Author

John Doe

Posted on

2021-06-03

Updated on

2021-06-08

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.