问题描述
在一个班级中,每位同学都拿到了一张卡片,上面有一个整数。有趣的是,除了一个数字之外,所有的数字都恰好出现了两次。现在需要你帮助班长小C快速找到那个拿了独特数字卡片的同学手上的数字是什么。
要求:
- 设计一个算法,使其时间复杂度为 O(n),其中 n 是班级的人数。
- 尽量减少额外空间的使用,以体现你的算法优化能力。
测试样例
样例1:
输入:
cards = [1, 1, 2, 2, 3, 3, 4, 5, 5]
输出:4
解释:拿到数字 4 的同学是唯一一个没有配对的。
样例2:
输入:
cards = [0, 1, 0, 1, 2]
输出:2
解释:数字 2 只出现一次,是独特的卡片。
样例3:
输入:
cards = [7, 3, 3, 7, 10]
输出:10
解释:10 是班级中唯一一个不重复的数字卡片。
约束条件
- 1 ≤ cards.length ≤ 1001
- 0 ≤ cards[i] ≤ 1000
- 班级人数为奇数
- 除了一个数字卡片只出现一次外,其余每个数字卡片都恰好出现两次
import java.sql.Array;
import java.util.Arrays;
public class Main {
public static int solution(int[] cards) {
// Edit your code here
Arrays.sort(cards);//这里使用了一次数组静态工具类排序方法,需要调用java.util.Arrays的包,注意数组的排序方法如何使用,与c++的不同之处在于前面要写Arrays
if(cards.length==1 || cards[0]!=cards[1]){
return cards[0];
}//先排除极端情况,如果只有一个数,或者该单独的数就是最小的那个数
else if(cards[cards.length-1]!=cards[cards.length-2]){
return cards[cards.length-1];
}//排除极端情况2,该单独的数是最大的那个数
else{
for(int i=0;i<cards.length; ){
if(cards[i]==cards[i+1]){
i=i+2;
}
else if(cards[i]!=cards[i+1]){
return cards[i];
}
}
}
return 0;//不要忽略最后的返回值ps 算法页面已具备
}
public static void main(String[] args) {
// Add your test cases here
System.out.println(solution(new int[]{1, 1, 2, 2, 3, 3, 4, 5, 5}) == 4);
System.out.println(solution(new int[]{0, 1, 0, 1, 2}) == 2);
}
}
毕业多年,最近又要把java捡起来了,从零开始学习,希望过往的c++经验能有点实用性。