地址:http://oj.leetcode.com/problems/single-number-ii/
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
那么除了头和尾外,如果一个数左右相邻的两个都不相等,那么必定就是那个数。
这题不应该就这么水过-_-!!
代码:
class Solution {
public:
int singleNumber(int A[], int n) {
sort(A, A+n);
for(int i = 0; i < n; ++i)
{
if(i==0)
{
if(A[i] != A[i+1])
{
return A[i];
}
}
else if(i==n-1)
{
if(A[i] != A[i-1])
{
return A[i];
}
}
else if(A[i] != A[i-1] && A[i] != A[i+1])
{
return A[i];
}
}
}
};
//int有32bit位,每位检测,如果出现1次或者4次,那么仅出现一次的数在这个bit位上肯定是1.
//SECOND TRIALclass Solution {public:int singleNumber(int A[], int n) {int ans = 0, bit_check = 0, bit_cnt = 0;for(int i = 0; i<=31; ++i){bit_check = 1<<i;bit_cnt = 0;for(int j = 0; j<n; ++j)if(A[j] & bit_check)++bit_cnt;if(bit_cnt % 3)ans |= bit_check;}return ans;}};
本文针对LeetCode上的单数III问题提供了两种解决方案。一种是通过排序后查找唯一出现一次的元素,另一种则是利用位操作高效求解,避免额外内存使用,符合线性时间复杂度的要求。
169

被折叠的 条评论
为什么被折叠?



