Find natural numbers that are not in a predetermined array

There is such an interesting question, ask:
There is such a non-repeating array of natural numbers, the length of the natural numbers is N, and the length of the array is N-2, and the natural numbers are randomly placed into the array in turn, please find 2 that are not put into it Natural number.
For example: this array of natural numbers is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] these ten numbers, and the order of random insertion is [2, 1, 3, 5, 7 , 9, 0, 4], then the numbers 6 and 8 are not included.
There are two ways to solve this problem

bucket sort solution

The idea of ​​bucket sorting is: Assuming the range of key values ​​is from 0 to N-1, we need buckets marked 0, 1, 2...N-1. If the element's key is i, then put the element into bucket i. In each bucket there is an element with the same value as the key.
This problem has 10 natural numbers and needs 10 buckets. Traverse this array, the array value is the subscript of the bucket, and the value is incremented by 1. Finally, check the bucket number, which bucket is empty (value 0) is a natural number that is not put in.

public class Ziranshu {

    public static void main(String[] args) {
        int[] a = {2, 1, 3, 5, 7, 9, 0, 4};
        int[] tong = new int[10];

        for(int i = 0; i < a.length; i++) {
            tong[a[i]] = 1;
        }

        for(int i = 0; i < tong.length; i++) {
            if(tong[i] == 0) {
                System.out.println(i);
            }
        }
    }

}

Solve the problem by using the Set non-repeating attribute

Set has the property of being unordered and not repeating. Of course, if you want to sort in descending order, you can use TreeSet. The idea is to put 8 elements into the set at a time, and then add elements to the existing set with a length of 8. The element value is the ten numbers between 0 and 9. If there is already a value in the set, size( ) length will not be changed, otherwise size() adds 1. If the length changes, print out the number currently added.

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class Ziranshu1 {

    public static void main(String[] args) {
        int[] a = {2, 1, 3, 5, 7, 9, 0, 4};
        Set<Integer> numbers = new TreeSet<Integer>();
        for(int i = 0; i < a.length; i++) {
            numbers.add(a[i]);
        }

        int length = numbers.size();
        for(int i = 0; i < 10; i++) {
            numbers.add(i);
            if(length != numbers.size()) {
                length = numbers.size();
                System.out.println(i + "不在内");
            }
        }
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325975721&siteId=291194637