标签:i+1 length .so 排序 find arrays element java bsp
Given an array of integers, every element appears twice except for one. Find that single one.
java(8ms):排序,然后跟相邻数字都不同的就是single one
1 public class Solution { 2 public int singleNumber(int[] nums) { 3 Arrays.sort(nums); 4 if (nums.length == 1) 5 return nums[0] ; 6 if (nums[0] != nums[1]){ 7 return nums[0] ; 8 }else if (nums[nums.length-1] != nums[nums.length-2]){ 9 return nums[nums.length-1] ; 10 } 11 for (int i = 1 ; i < nums.length-1 ; i++){ 12 if (nums[i] != nums[i-1] && nums[i] != nums[i+1]){ 13 return nums[i] ; 14 } 15 16 } 17 return 0 ; 18 } 19 }
java(1ms):相同的数异或后为0,将所有的数异或,最后剩下single one
1 public class Solution { 2 public int singleNumber(int[] nums) { 3 for (int i = 1 ; i < nums.length ; i++){ 4 nums[0] ^= nums[i] ; 5 } 6 return nums[0] ; 7 } 8 }
标签:i+1 length .so 排序 find arrays element java bsp
原文地址:http://www.cnblogs.com/-Buff-/p/6006131.html