Monday, 27 June 2016

Basic easy level programs

Basic Programs:
1.Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Solution:
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}
2. Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time
Solution:
    public int firstMissingPositive(int[] nums) {
     Map<Integer, Integer> map=new HashMap<>();
         for(int i=0;i<nums.length;i++)
   map.put(i,nums[i]);
int num = 0,x=0;
for(int i=1;i<Integer.MAX_VALUE;i++)
  {
     if(!map.containsValue(i))
    { num=i;
                                break;}
    }return num;  }

No comments:

Post a Comment