您的位置:首页 > 其它

TwoSum问题

2016-04-06 13:55 113 查看
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].
我的算法public int[] solution(int[] nums,int target){Map<Integer,Integer> map=new HashMap<Integer,Integer>();int[] res=new int[2];for(int i=0;i<nums.length;i++){if(map.containsKey(target-nums[i])){res[0]=i;res[1]=map.get(target-nums[i]);}map.put(nums[i], i);}return res;}网上还有一种不使用HashMap的方法,但是当数组中有重复的数出现时可能会出现数组越界问题public int[] solution2(int[] nums,int target){int[] nums_sorted=new int[nums.length];System.arraycopy(nums,0, nums_sorted, 0, nums.length);Arrays.sort(nums_sorted);int start=0;int end=nums_sorted.length;while(start<end){while(nums_sorted[start]+nums_sorted[--end]>target);if(nums_sorted[start]+nums_sorted[end]==target)break;while(nums_sorted[++start]+nums_sorted[end]<target);if(nums_sorted[end]+nums_sorted[start]==target)break;}int[] res=new int[2];int index=0;int a=nums_sorted[start];int b=nums_sorted[end];for(int i=0;i<nums.length;i++){if(nums[i]==a||nums[i]==b)res[index++]=i;}return res;}加油!
b662
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: