首先,可以排序,之后遍历,不过时间复杂度是nlogn,代码如下,不细说
class Solution { public int singleNumber(int[] nums) { Arrays.sort(nums); if(nums.length==1)return nums[0]; int length=nums.length; //int shu=nums[0]; int sum=0; int cur=nums[0]; for(int i=0;i<length;) { if(nums[i]==nums[i+1]) { i=i+2; } else { return nums[i]; } if(i==length-1) { return nums[i]; } } return -1000; } }
其次,https://leetcode-cn.com/problems/single-number/solution/zhi-chu-xian-yi-ci-de-shu-zi-by-leetcode/
class Solution { public int singleNumber(int[] nums) { int a = 0; for (int i : nums) { a ^= i; } return a; } }