Java implementation LeetCode 645 error collection (violence)

645. error collection

Set S contains an integer from 1 to n. Unfortunately, because of data errors, which led to a collection of a certain element replicates the value Another element which has become a collection, resulting in the loss of a set of integers and there is an element of repetition.

Given an array nums represents the result of the set S error occurred. Your task is to first find a recurring integer, to find the missing integer, returns them as an array.

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]
Note:

The length of the array is given range [2, 10 000].
Given array is disordered.

class Solution {
   public int[] findErrorNums(int[] nums) {
        
        int[] counter = new int[nums.length+1];
        
        for (int i: nums) {
            counter[i]++;
        }
        
        int[] result = new int[2];
        for (int i = 1; i<counter.length; i++) {
            if (counter[i] == 0) {
                result[1] = i;
            } else if (counter[i] == 2) {
                result[0] = i;
            }
        }
        
        return result;
    }
}
Released 1699 original articles · won praise 30000 + · views 3.38 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105266500