[lintcode medium]Find the Missing Number

Find the Missing Number

Given an array contains N numbers of 0 .. N, find which number doesn't exist in the array.

Example

Given N = 3 and the array [0, 1, 3], return 2.

Challenge

Do it in-place with O(1) extra memory and O(n) time.

 

public class Solution {
    /**    
     * @param nums: an array of integers
     * @return: an integer
     */
    public int findMissing(int[] nums) {
        // write your code here
        if(nums.length==0) return -1;
        int n=nums.length;
        int result=n;
        
        for(int p=0;p<n;p++)
        {
           boolean found=false;
           for(int j=p;j<n;j++)
           {
              if(nums[j]==p && j==p)
              {
                  found=true;
                  break;
              }
              else
              if(nums[j]==p && j!=p)
              {
                 int temp=nums[p];
                 nums[p]=nums[j];
                 nums[j]=temp;
                 found=true;
              }
           }
           if(!found)
           {
               result=p;
               break;
           }
        }
        return result;
    }
}

 

posted on 2015-12-10 06:07  一心一念  阅读(159)  评论(0编辑  收藏  举报

导航