How to tell if an array is a permutation in O(n)?

后端 未结 16 1594
粉色の甜心
粉色の甜心 2020-12-07 10:17

Input: A read-only array of N elements containing integer values from 1 to N (some integer values can appear more than once!). And a memory zone of a fixed<

16条回答
  •  有刺的猬
    2020-12-07 10:22

    Java solution below answers question partly. Time complexity I believe is O(n). (This belief based on the fact that solution doesn't contains nested loops.) About memory -- not sure. Question appears first on relevant requests in google, so it probably can be useful for somebody.

    public static boolean isPermutation(int[] array) {   
        boolean result = true;
        array = removeDuplicates(array);
        int startValue = 1;
        for (int i = 0; i < array.length; i++) {
            if (startValue + i  != array[i]){
                return false;
            }
        }
        return result;
    }
    public static int[] removeDuplicates(int[] input){
        Arrays.sort(input);
        List result = new ArrayList();
        int current = input[0];
        boolean found = false;
    
        for (int i = 0; i < input.length; i++) {
            if (current == input[i] && !found) {
                found = true;
            } else if (current != input[i]) {
                result.add(current);
                current = input[i];
                found = false;
            }
        }
        result.add(current);
        int[] array = new int[result.size()];
        for (int i = 0; i < array.length ; i ++){
            array[i] = result.get(i);
        }
        return array;
    }
    public static void main (String ... args){
        int[] input = new int[] { 4,2,3,4,1};
        System.out.println(isPermutation(input));
        //output true
        input = new int[] { 4,2,4,1};
        System.out.println(isPermutation(input));
        //output false
    }
    

提交回复
热议问题