题目:Single Number
描述:Given an array of integers, every elements appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Java code:
public class Solution {
public int singleNumber(int[] A) {
int res = 0;
for (int i = 0; i < A.length; i++){
res = res^A[i];
}
return res;
}
}①数组长度:length在数组中为属性,使用时A.length;length()在字符串中为方法,表示字符串长度,使用时str.length()
size()用于泛型集合,求集合中的元素的个数
有个int数,int a = 1234567890,求a 的长度:a.toString().length()
②java中的异或运算
异或运算的特点:a 自己与自己异或为0
b 异或满足交换律,多个int进行异或,中间顺序可以任意改变 A xor B xor A = B
c 0 xor a = a
③采用异或运算,进行两两比较,每次在比较array中加入一个元素,一旦有相同元素在比较array中,就可以两两相消
这样运算的复杂度为X(n),复杂度比较低,只需要进行一次循环比较
方法二:
public class Solution {
public int singleNumber(int[] A) {
int n = A.length;
for (int i = 0; i < n; i++){
for( int j = 0; j < n; j++){
if(i == j){
continue;
}else if(A[i] == A[j]){
break;
}else continue;
}
if(j == n){
return A[i];
}
}
}
}①使用这种方法,有两种循环,外循环作为比较的标杆,内循环中每个数字与标杆进行比较。两层循环的复杂度为X(n^2),比方法一要复杂,所以在leetcode中没有被accept
②for循环中 break是跳出整个所在循环,例如j循环中的break是跳出j循环
continue是跳出当前循环,例如j=1时continue是跳出j=1这种情况,继续j=2的循环
本文介绍如何在Java中解决单数查找问题,通过异或运算实现算法,阐述其原理与复杂度,并对比不同解决方案的优劣。
1003

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



