[数组]645. Set Mismatch

题目:645. Set Mismatch

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.

一个数组含有1到n的数组,然而里面有一个数字重复了使得另一个数字缺失了,找到这两个数字。数组无排序,size一定。

用了一个很笨的办法。遍历第一遍找出重复的数字,并把不重复的数字加入set。再遍历一遍set找出那个缺失的数字。效率一般。

class Solution {
    public int[] findErrorNums(int[] nums) {
        int len = nums.length;
        int[] res = new int[2];
        if(len == 0) return res;
        Arrays.sort(nums);
        Set<Integer> set = new HashSet<Integer>();
        for(int i = 1; i <= len ; i++){
            if(set.contains(nums[i-1])){
                res[0] = nums[i-1];
            }else{
                set.add(nums[i-1]);
            }
        }
        for(int i = 1;i<= len ;i++){
            if(!set.contains(i)){
                res[1] = i;
                break;
            }
        }
        return res;
    }
}

solution里优秀的解法:
都不需要排序。

class Solution {
    public int[] findErrorNums(int[] nums) {
        int[] res = new int[2];
        
        for(int i = 0 ; i < nums.length ; i++) {
            if(nums[Math.abs(nums[i]) - 1] < 0) {
                res[0] = Math.abs(nums[i]);//遇到重复的index,该nums[index -1] 已为负
            }
            else {
                nums[Math.abs(nums[i]) - 1] *= -1; //将所有不重复的数作index的位为标为-;
            }
        }
        for(int i = 0 ; i < nums.length ; i++) {
            if(nums[i] > 0) {
                res[1] = i + 1; //未被标记的index即为缺失的index
            }
        }
        return res;
    }

}

更高级的解法:

class Solution {
    public int[] findErrorNums(int[] nums) {
        int[] occur = new int[nums.length];
        int dup = 0, miss = 0;
        for (int n : nums) {
            occur[n-1]++;
            if (occur[n-1] == 2) dup = n;
        }
        for (int i = 0;i < nums.length;i++) {
            if (occur[i] == 0) miss = i+1;
        }
        
        return new int[]{dup, miss};
    }
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容