Problem:
Given an 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?
public class Solution {
public int singleNumber(int[] nums) {
Arrays.sort(nums);
if (nums.length == 1 || nums[0] != nums[1]){ //数组可能只有一个元素
return nums[0];
}
for(int i = 1; i < nums.length-1; i++){
if((nums[i] != nums[i-1]) && (nums[i] != nums[i+1])){
return nums[i];
}
}
return nums[nums.length - 1]; //我的方法好像比较笨
}
}Code2:
public class Solution {
public int singleNumber(int[] nums) {
int n = 0;
for(int i = 0; i < nums.length; i++){
n = n ^ nums[i]; //这类题有个大杀器叫异或!!!
}
return n;
}
}
本文介绍了一种在整数数组中查找唯一不重复元素的方法,该方法具备线性时间复杂度,并探讨了如何通过异或操作高效实现。此外,文章还提供了一种排序后遍历数组的解决方案。

2374

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



