LeetCode 645 : Set Mismatch(java)

2507 ワード

原題
The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number. Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.
Example 1: Input: nums = [1,2,2,4] Output: [2,3]
Note: The given array size will in the range [2, 10000]. The given array’s numbers won’t have any order.
構想
題意は大体以下の通りである:set Sの長さはnであり、無秩序に数字1-nを格納しているが、data errorのため、1つの数字が重複(同時に1つの数字が欠落していることを意味する)し、重複数字と欠落した数字を探し出す.1つのmap、1回目のループでset Sを1回通過し、出現した数字をmapでマークし、同時に重複した数字(マークされた数字は2回目に重複した数字と読む)を記録する.2回目のループでmapを1回通過し、欠落した数字(マークされていない数字)を検索します.時間複雑度はo(n)である.
コード#コード#
public class Solution {
    public int[] findErrorNums(int[] nums) {
        int res[]=new int[2];
        //boolean        false
        boolean map[]=new boolean[nums.length+1];
        for(int i=0;iif(map[nums[i]]==false)
                map[nums[i]]=true;
            else
                res[0]=nums[i];
        for(int i=1;i1);i++)
            if(map[i]==false){
                res[1]=i;
                break;
            }
        return res;
    }
}