|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- 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
复制代码
- class Solution {
- public int singleNumber(int[] nums) {
-
- if(nums.length == 0) return 0;
-
- if(nums.length == 1) return nums[0];
-
- Arrays.sort(nums);
-
- for(int i = 1; i< nums.length;i++ ){
-
- if(nums[i] == nums[i-1]) continue;
-
- else{
- if(i == nums.length-1) return nums[i];
-
- if(i == 1) return nums[i-1];
-
- if(nums[i] == nums[i+1]) i++;
-
- else{ return nums[i]; }
- }
- }
-
-
- return 0;
- }
- }
复制代码
- class Solution {
- public int singleNumber(int[] nums) {
-
- int re = 0;
-
- for(int i = 0 ; i < nums.length; i++) re = re ^ nums[i];
-
- return re;
- }
- }
复制代码 |
|