Given an array of integers, find the first missing positive integer in linear time and constant space

后端 未结 15 2240
暖寄归人
暖寄归人 2021-02-01 07:17

In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. This question was asked by Stri

15条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 08:00

    This is in Java. Time complexity f O(N) and space complexity O(1)

    private static int minimum_positive_integer(int[] arr) {
            int i = 0;
            int j = arr.length - 1;
    
            //splitting array
            while (i < j) {
                if (arr[i] > 0) {
                    i++;
                }
    
                if (arr[j] <= 0) {
                    j--;
                }
    
                if (arr[i] <= 0 && arr[j] > 0) {
                    int t = arr[i];
                    arr[i] = arr[j];
                    arr[j] = t;
    
                    i++;
                    j--;
                }
            }
            int len_positive = i;
    
            if (arr[i] > 0) len_positive++;
    
            for (i = 0; i < len_positive; i++) {
                int abs = Math.abs(arr[i]);
                if (abs <= len_positive) {
                    int index = abs - 1;
                    arr[index] = -abs;
                }
            }
    
            for (i = 0; i < len_positive; i++) {
                if(arr[i] > 0) return  i + 1;
            }
    
            return len_positive + 1;
        }
    

提交回复
热议问题