Find 2 missing numbers in an array of integers with two missing values

前端 未结 12 1176
梦谈多话
梦谈多话 2021-01-30 09:33

How do you do this? The values are unsorted but are of [1..n] Example array [3,1,2,5,7,8]. Answer: 4, 6

I saw this solution in

12条回答
  •  忘掉有多难
    2021-01-30 10:24

    #include 
    using namespace std;
    int main() {
        int arr[]={3,1,2,5,7,8};
        int n=6;
        for(int i=0;i0 && arr[i]<=n){
                int temp=arr[i]-1;
                if(arr[i]!=arr[temp]){
                swap(arr[i],arr[temp]);
                i--;
                }
            }
        }
        for(int i=0;i

    We can use the same array as a bucket. We traverse it once and keep on swapping the element to their correct index. If the value is less than 1 or more than array length, we leave it as it is. Initial Array- 3 1 2 5 7 8 swap(3,5) 5 1 2 3 7 8 swap(5,8) 8 1 2 3 7 5 After this we again traverse the array. The elements which are not in their proper position are missing hence we print the index. Time Complexity-O(n)

提交回复
热议问题