two sum

来源:互联网 发布:星球大战 全介绍 知乎 编辑:程序博客网 时间:2024/06/14 21:44

question:

Given: an array of integers, 

to do: find two numbers such that they add up to a specific target number.

requirement: The function twoSum should return indices of the two numbers 

                        such that they add up to the target, where index1 must be less 

                        than index2. Please note that your returned answers (both index1 

                        and index2) are not zero-based.


You may assume that each input would have exactly one solution.


Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

public class Solution{

        public int[] twoSum(int[] nums, int target){

                  for(int i=0; i<nums.length; i++){

                            for(int j=0; j<nums.length; j++){

                                    int sum = nums[i]+nums[j];

                                    if(sum==target && (i<j>)){

                                            System.out.println("Output: index1=" + (i+1) +", index2=" + (j+1));

                                  }

                            }

                  }

                 return nums=null;

        }

}


error message:; last executed input: time limited exceed.

using mapping


public class Solution{

       public int[] twoSum(int[] nums, int target){

              Map<Integer, Integer> map = new HashMap<>();

              for(int i=0; i<nums.length; i++){

                         int x = nums[i];

                         if(map.containsKey(target - x)){

                                    return new int[]{map.get(target - x) + 1, i+1};

                         }

                         map.put(x,i);

              }

              throw new IllegalArgumentException("No two sum solution");

       }

}

brute force approach has O(n^2) run time and O(1) space.

hash table has O(n) run time and O(n) space.


       

0 0
原创粉丝点击