0645. Set Mismatch (E)

Set Mismatch (E)

题目

You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

You are given an integer array nums representing the data status of this set after the error.

Find the number that occurs twice and the number that is missing and return them in the form of an array.

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]

Example 2:

Input: nums = [1,1]
Output: [1,2]

Constraints:

  • 2 <= nums.length <= 10^4
  • 1 <= nums[i] <= 10^4

题意

给定长度为n的数组,包含整数1-n,将其中一个数字替换为另一个1-n中的数字,要求找到重复的数字和被替换的数字。

思路

第一次遍历,找到重复的数字,并把数字x放到下标为x-1的位置;第二次遍历,找到被替换的数字,即不满足nums[i]==i+1的位置。


代码实现

Java

class Solution {
    public int[] findErrorNums(int[] nums) {
        int rep = 0, loss = 0;
        for (int i = 0; i < nums.length; i++) {
            int j = nums[i] - 1;
            if (i == j) continue;
            if (nums[i] == nums[j]) {
                rep = nums[i];
            } else {
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;
                i--;		// 交换后还需要判断交换后的当前位置
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i + 1) {
                loss = i + 1;
                break;
            }
        }
        return new int[]{rep, loss};
    }
}
posted @ 2021-03-02 16:30  墨云黑  阅读(52)  评论(0编辑  收藏  举报