Missing Number

 

 

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

HashMap!

 1     public int missingNumber(int[] nums) 
 2     {
 3         Map<Integer,Integer> map = new HashMap<>();
 4         for(int i = 0; i < nums.length;i++)
 5         {
 6             map.put(nums[i],nums[i]);
 7         }
 8         
 9         int j;
10         for(j=0;j<nums.length;j++)
11         {
12             if(!map.containsKey(j))
13             break;
14         }
15         
16         return j;
17     }

 

posted @ 2015-10-07 11:18  Hygeia  阅读(117)  评论(0编辑  收藏  举报