美文网首页
LeetCode刷题之Set Mismatch

LeetCode刷题之Set Mismatch

作者: JRTx | 来源:发表于2017-09-04 20:51 被阅读0次

    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};
    }
    

    相关文章

      网友评论

          本文标题:LeetCode刷题之Set Mismatch

          本文链接:https://www.haomeiwen.com/subject/xeqyjxtx.html