集合 s
包含从 1
到 n
的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。
给定一个数组 nums
代表了集合 S
发生错误后的结果。
请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。
示例 1:
输入:nums = [1,2,2,4] 输出:[2,3]示例 2:
输入:nums = [1,1] 输出:[1,2]提示:
2 <= nums.length <= 104
1 <= nums[i] <= 104
第一种解法:先排序,根据题目1-n的特性找异常
自己想的解法。试着复习了昨天学习的TreeSet,运用有序、无重复的特性,但发现需要再度遍历一次判断重复,所以弃用了。时间复杂度是O(nlogn),应该是排序的缘故。。加深了边界情况的理解。
import java.util.Arrays;
class Solution {
public int[] findErrorNums(int[] nums) {
int[] result = new int[2];
Arrays.sort(nums);//排序
for(int i = 1;i < nums.length;i++){
if(nums[i] == nums[i-1]){//判断重复
result[0] = nums[i];
}
if(nums[i] == nums[i-1] + 2){//判断缺少
result[1] = nums[i-1] + 1;
}
}
if(nums[0] != 1){//边界情况
result[1] = 1;
}else if(nums[nums.length-1] != nums.length){
result[1] = nums.length;
}
return result;
}
}
第二种解法:异或
精进了异或方面的理解。学会了return的新写法。。
class Solution {
public int[] findErrorNums(int[] nums) {
int n = nums.length;
int xorAll = 0;
// 计算数组的总异或值
for (int num : nums) {
xorAll ^= num;
}
// 计算1到n的总异或值
for (int i = 1; i <= n; i++) {
xorAll ^= i;
}
// 找到最低位不同的位
int diffBit = xorAll & (-xorAll);
int xor0 = 0, xor1 = 0;
// 根据diffBit将数字分成两组
for (int num : nums) {
if ((num & diffBit) != 0) {
xor1 ^= num;
} else {
xor0 ^= num;
}
}
for (int i = 1; i <= n; i++) {
if ((i & diffBit) != 0) {
xor1 ^= i;
} else {
xor0 ^= i;
}
}
// 确定哪个是重复的数字,哪个是丢失的数字
for (int num : nums) {
if (num == xor0) {
return new int[]{xor0, xor1};
}
}
return new int[]{xor1, xor0};
}
}
一些废话
好久没写代码了特别手生,本月的第四道力扣题,easy每道题要写两个小时,虽然能写出来,一运行就发现有问题。今天发现新建int数组都忘记写法了,大受挫败。不求dp,只求能够写完一道题学会新的东西,想先找到写代码题的快乐。
感觉稍微找到一些手感和模糊的思路了,希望一周后easy题可以半小时内做完+订对吧~