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};
        }
    }
    
  • 相关阅读:
    SQLAlchemy使用说明之ORM
    Python日志模块logging
    Python正则表达式模块re
    group by 小结
    Hive Beeline 官方文档学习
    在MySQL中创建cm-hive使用的数据库及账号
    MySQL导入数据错误error: 13 及解决办法
    Yum 安装并设置 MySQL
    使用xshell5 从CentOS主机download资料
    Bootstrap 学习
  • 原文地址:https://www.cnblogs.com/mapoos/p/14469646.html
Copyright © 2011-2022 走看看