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};
        }
    }
    
  • 相关阅读:
    php日常日志写入格式记录
    ssh 配置config 别名
    win10 使用docker
    gulp watch error ENOSPC
    log4net各种Filter使用【转】
    【转】Controllers and Routers in ASP.NET MVC 3
    【转】ASP.NET MVC学习笔记-Controller的ActionResult
    JavaScript 面向对象程序设计(下)——继承与多态 【转】
    Ajax– 刷新页面 【转】
    [webgrid] – selecterow
  • 原文地址:https://www.cnblogs.com/mapoos/p/14469646.html
Copyright © 2011-2022 走看看