Single Number系列
Single Number
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:
1 | Input: [2,2,1] |
Example 2:
1 | Input: [4,1,2,1,2] |
可能的解法有:排序后判断元素出现次数。
解法1:排序
排序后查找每个元素是否只出现了一次,直到找到那个只出现了一次的元素。
1 | class Solution { |
时间复杂度:O(nlogn)
空间复杂度:O(logn)
解法2:位运算
1 | // 这里定义了一个lambda表达式并调用该表达式 |
Single Number II
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:
1 | Input: [2,2,3,2] |
Example 2:
1 | Input: [0,1,0,1,0,1,99] |
解法1:
k个相同的k进制数进行无进位相加,结果一定是每一位都为0的k进制数。
1 | class Solution { |