Single Number 落单的数
Description
Given 2 * n + 1 numbers, every numbers occurs twice except one, find it.
public class Solution {
/**
* @param A: An integer array
* @return: An integer
*/
public int singleNumber(int[] A) {
// write your code here
if(A.length == 1){
return A[0] ;
}
Arrays.sort(A) ;
for(int i = 0 ; i < A.length ; i++){
if(i == 0 && A[i] != A[i+1]){
return A[i] ;
}
if(i < A.length-1 && i > 0 && A[i] != A[i-1] && A[i] != A[i+1]){
return A[i] ;
}
}
return A[A.length-1] ;
}
}
public class Solution {
/**
* @param A: An integer array
* @return: An integer
*/
public int singleNumber(int[] A) {
// write your code here
if(A == null || A.length==0){
return -1 ;
}
int res = 0 ;
for(int i = 0 ; i < A.length ; i++){
res ^= A[i] ;
}
return res ;
}
}
该博客介绍了两种方法来解决编程问题,即在给定的数组中找到唯一出现一次的数字。第一种方法通过排序数组并比较相邻元素来找到单数;第二种方法使用位运算符异或(^)来找出不同寻常的数字。这两种解决方案都适用于2n+1个数字,其中每个数字都出现两次,除了一个。
785

被折叠的 条评论
为什么被折叠?



