首页 > 代码库 > 136. Single Number

136. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

一个int型数组,除了其中一个元素以外,其他的均出现两次。

 

My Solution:

 1     public int singleNumber(int[] nums) {
 2         //Sort this array in an ascending order.
 3         Arrays.sort(nums);
 4         int x = 0;
 5         /*    Elements will appear in pair except for one.
 6          *     Increase the subscript of this array progressively by 2.
 7          *     The one unequal to its next or the last one left would be returned.
 8          */
 9         for(int i = 0; i<nums.length ;i += 2){
10             if(i + 1 == nums.length || nums[i] != nums[i+1]){
11                 x = nums[i];
12                 break;
13             }
14         }
15         return x;
16     }

 

 

Others‘ Solution:

 1 /*  We use bitwise XOR to solve this problem :
 2 
 3     First , we have to know the bitwise XOR in java
 4 
 5     0 ^ N = N
 6     N ^ N = 0
 7     So..... if N is the single number
 8 
 9     N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ Nx ^ N
10 
11     = (N1^N1) ^ (N2^N2) ^..............^ (Nx^Nx) ^ N
12 
13     = 0 ^ 0 ^ ..........^ 0 ^ N
14 
15     = N 
16  */
17 
18 
19 public int singleNumber(int[] nums) {
20     int ans =0;
21     
22     int len = nums.length;
23     for(int i=0;i!=len;i++)
24         ans ^= nums[i];
25     
26     return ans;
27 }

 

136. Single Number