LeetCode刷题实战136:只出现一次的数字
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
题意
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
解题
public static int singleNumber(int[] nums) {
int num = 0;
for (int i = 0; i < nums.length; i++) {
num = num ^ nums[i];
}
return num;
}
public static int singleNumber(int[] nums) {
Setset = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (!set.add(nums[i])) { // add成功返回true,如果set中已有相同数字,则add方法会返回false
set.remove(nums[i]); // 删除重复出现的数字
}
}
return set.iterator().next(); }
public static int singleNumber(int[] nums) {
int num = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
// 偶数下标位置 num += nums[i],奇数下标位置 num -= nums[i]
num = i % 2 == 0 ? num + nums[i] : num - nums[i];
}
return num;
}
public static int singleNumber(int[] nums) {
int num = 0;
for (int i = 0; i < nums.length; i++) {
num = num ^ nums[i];
}
return num;
}
评论