码迷,mamicode.com
首页 > 其他好文 > 详细

136. Single Number

时间:2017-01-31 15:11:11      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:span   air   end   ever   app   bit   bsp   increase   element   

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

标签:span   air   end   ever   app   bit   bsp   increase   element   

原文地址:http://www.cnblogs.com/luojunc/p/6358823.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!