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:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
题目:给定一个非空整数数组,数组中有1个数只出现1次、其他数都出现2次,找出只出现1次的数。要求算法的时间复杂度是O(n)、空间复杂度是O(1)。
实现思路1(不满足时间复杂度要求):一种直观的做法是将数组排序,出现2次的数会出现在一起,因此两两检查,如果发现不相同的数或者最后只剩余一个数就找到了最终结果。这种算法的空间复杂度是O(1),但时间复杂度是O(nlogn)。
class Solution {
public int singleNumber(int[] nums) {
if (nums == null) throw new IllegalArgumentException("argument is null");
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i += 2)
if (nums[i] != nums[i + 1])
return nums[i];
return nums[nums.length - 1];
}
}实现思路2(不满足空间复杂度要求):另一种直观的做法是用一个List保存数组中的数,如果当前遍历的数已经在List中则将这个数删除,否则就将这个数添加进List。由于数组中只有1个数出现1次且其他数都出现2次,因此这个List最终只会有1个数(最终结果)。这种算法的时间复杂度是O(n),但空间复杂度是O(n)。
class Solution {
public int singleNumber(int[] nums) {
if (nums == null) throw new IllegalArgumentException("argument is null");
List<Integer> list = new ArrayList<>();
for (int i : nums) {
if (list.contains(i))
list.remove(new Integer(i));
else
list.add(i);
}
return list.get(0);
}
}实现思路3(满足题目要求):利用异或运算的特性,即a^b^a=b。由于数组中只有1个数出现1次,其余数都出现2次,因此令所有数做异或运算的结果就是题目要求的最终结果。
class Solution {
public int singleNumber(int[] nums) {
if (nums == null) throw new IllegalArgumentException("argument is null");
int result = nums[0];
for (int i = 1; i < nums.length; i++)
result = result ^ nums[i];
return result;
}
}参考资料:
https://leetcode.com/problems/single-number/solution/
本文介绍了一种算法问题:在一个非空整数数组中找到只出现一次的数字,其他数字均出现两次。提出了三种解决方案,包括排序、使用额外列表以及利用异或运算特性,最终推荐了时间复杂度为O(n)且空间复杂度为O(1)的异或运算方法。

1799

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



