您的位置:首页 > 编程语言 > Java开发

jiler的LeetCode学习笔记 java版本Two Sum

2015-03-13 23:06 387 查看
Given an array of integers, find two numbers such that they add up to a specific target number.
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
问题描述: 给你一系列整型值,找到其中的两个数,使他们相加等于给的target。函数结果返回两个数的位置。并且第一个下标比第二个小。注意,两个下标不是以0开始的。
问题是 复杂度,也就是效率。提示中给了可以使用HashMap。下面是我的代码,不当之处多多批评:
//思路1:两个for嵌套循环,时间超时
    //思路2:一个循环数组,复杂度为o(n);总和减去这个,另一个在数组另存为的hashmap中查找,这样效率极高。
        public int[] twoSum(int[] numbers, int target) {
            int[] index ={0,0};
            int flag = 0;
            HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
            for(int i=0;i<numbers.length;i++){
                hm.put(numbers[i], i);             
            }
                                            
            for(int j=0;j<numbers.length;j++){
                Integer another = hm.get((target - numbers[j]));
                if(another != null && another != j ){
                    index[0]=j+1;
                    index[1]=another+1;
                    break;
                }
                    
            }
            return index;
        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: