Algorithm to determine if array contains n…n+m?

前端 未结 30 3178
清酒与你
清酒与你 2020-11-28 01:45

I saw this question on Reddit, and there were no positive solutions presented, and I thought it would be a perfect question to ask here. This was in a thread about interview

30条回答
  •  我在风中等你
    2020-11-28 02:00

    Here is a solution in O(N) time and O(1) extra space for finding duplicates :-

    public static boolean check_range(int arr[],int n,int m) {
    
            for(int i=0;i=m)
                    return(false);
            }
    
            System.out.println("In range");
    
            int j=0;
            while(j

    Explanation:-

    1. Bring number to range (0,m-1) by arr[i] = arr[i] - n if out of range return false.
    2. for each i check if arr[arr[i]] is unoccupied that is it has value less than m
    3. if so swap(arr[i],arr[arr[i]]) and arr[arr[i]] = arr[arr[i]] + m to signal that it is occupied
    4. if arr[j] = j and simply add m and increment j
    5. if arr[arr[j]] >=m means it is occupied hence current value is duplicate hence return false.
    6. if arr[j] >= m then skip

提交回复
热议问题