首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。