zoukankan      html  css  js  c++  java
  • 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};
        }
    }
    
  • 相关阅读:
    计算机网络基础
    计算机网络之应用层
    计算机网络之传输层
    计算机网络之网络层
    计算机通信之数据链路层
    fastjson =< 1.2.47 反序列化漏洞浅析
    你没有见过的加密
    CTF MD5之守株待兔,你需要找到和系统锁匹配的钥匙
    Redis 4.x 5.x 未授权访问
    redis安装
  • 原文地址:https://www.cnblogs.com/mapoos/p/14469646.html
Copyright © 2011-2022 走看看