Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
do it in linear time complexity and constant extra space.

iterate them once, and we can only use swap (at least it looks like we have to do it in this way)
method 1:

class Solution {
    public int missingNumber(int[] nums) {
        //method 1, mathmatical 
        int sum = 0;
        for (int num: nums) {
            sum += num;
        }
        int length = nums.length;
        int origin = length * (length + 1) / 2;
        return origin - sum;
    }
}

method2:
swap everything to its right position, and iterate it to check. if we have i != nums[i], then that’s the missing number.

class Solution {
    public int missingNumber(int[] nums) {
        //method 2, swap
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != nums.length) {
                swap(nums, i, nums[i]);
            }
            System.out.println(nums[i]);
        }
        //then we can make sure everything is in the right position except the element that equals to nums.length
        
        //iterate everything, if someone is not in the postion, then return that index, else return length
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i) {
                return i;
            }
        }
        return nums.length;
    }
    
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
posted @ 2020-09-12 23:54  EvanMeetTheWorld  阅读(22)  评论(0)    收藏  举报