LeetCode 645 Set Mismatch
概述
https://leetcode.com/problems/set-mismatch/
布尔数组记录法
class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
vector<bool> exist(nums.size() + 1, false);
vector<int> ans = {-1, -1};
for (auto n : nums) {
if (exist[n]) ans[0] = n;
exist[n] = true;
}
for (int i = 1; i < nums.size() + 1; i ++) {
if (!exist[i]) {
ans[1] = i;
break;
}
}
return ans;
}
};
通过将原数组中值取反的方式进行记录
class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
vector<int> ans = {-1, -1};
for (int i = 0; i < nums.size(); i ++) {
if (nums[abs(nums[i])-1] < 0) {
ans[0] = abs(nums[i]);
} else {
nums[abs(nums[i])-1] *= -1;
}
}
for (int i = 0; i < nums.size(); i ++) {
if (nums[i] > 0) {
ans[1] = i + 1;
break;
}
}
return ans;
}
};
Links: leetcode-645-set-mismatch