LeetCode 645 Set Mismatch

标签: 数学类题目 LeetCode 发布于:2022-02-24 23:59:02 编辑于:2022-02-25 00:07:55 浏览量:921

概述

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;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/