题目分别是:
Given an array of integers, every element appears twice except
for one. Find that single one.
Given an array of integers, every element appears three times
except for one. Find that single one.
开始考虑使用hashtable存储内容,查找,看了discuss发现使用异或这个方法
问题一的代码如下:
public class Solution {
public int singleNumber(int[] A) {
int i = 0;
int result = 0;
for (i=0; i<=A.length-1; i++){
result = result ^ A[i];
} return result;
}
}
问题二看了discuss 发现神解答如下:http://oj.leetcode.com/discuss/857/constant-space-solution
本文介绍了解决数组中寻找唯一出现一次的元素的问题。针对元素出现两次和三次的情况,提供了高效的解决方案,利用异或运算来实现。对于出现两次的情况,直接通过异或解决;而对于出现三次的情况,则需要更复杂的逻辑。
5983

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



