LeetCode刷题之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:

  1. The given array size will in the range [2, 10000].
  2. The given array's numbers won't have any order.

My Solution:

class Solution {
    public int[] findErrorNums(int[] nums) {
        int[] result = new int[2];
        int[] flag = new int[nums.length + 1];
        int i;
        for (i = 0; i < nums.length; ++i) {
            flag[nums[i]]++;
            if (flag[nums[i]] == 2) {
                result[0] = nums[i];
            }
        }
        for (i = 1; i <= nums.length; ++i) {
            if (flag[i] == 0) {
                result[1] = i;
                break;
            }
        }
        return result;
    }
}

Great Solution1:

public int[] findErrorNums(int[] nums) {
    Map < Integer, Integer > map = new HashMap();
    int dup = -1, missing = 1;
    for (int n: nums) {
        map.put(n, map.getOrDefault(n, 0) + 1);
    }
    for (int i = 1; i <= nums.length; i++) {
        if (map.containsKey(i)) {
            if (map.get(i) == 2)
                dup = i;
        } else
            missing = i;
    }
    return new int[]{dup, missing};
}

Great Solution2:

public int[] findErrorNums(int[] nums) {     
    int dup = -1, missing = 1;
    for (int n: nums) {
        if (nums[Math.abs(n) - 1] < 0)
            dup = Math.abs(n);
        else
            nums[Math.abs(n) - 1] *= -1;
    }
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] > 0)
            missing = i + 1;
    }
    return new int[]{dup, missing};
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,418评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,789评论 0 23
  • 等我们老的时候,那时的你,心中掠过的不知是哪个熟悉的身影, 不知是哪一段刻骨铭心的记忆。 时间会改变一切,包括我们...
    fb221de0b9ab阅读 397评论 1 1
  • 爸爸这几天在家,孩子们会围着爸爸玩,他啊就是个娃娃头,和孩子蹦来蹦去.跑来跑去,各种玩法,也不嫌麻烦。现...
    爱你的贝贝阅读 237评论 0 3
  • 散文小说诗歌: 《爱默生随笔》| 爱默生 链接 《白夜行》| 东野圭吾 链接 《王维孟浩然诗选评》| 陶文鹏 链接...
    朱小虎XiaohuZhu阅读 875评论 9 5