Two Sum

       欢迎来到LeetCode的世界,本人程序员一枚,灰常菜的那种,目前处于找工作时期,正在刷LeetCode上的题目,希望通过自己写博客能记下自己的思路与成长,也希望能帮助到有需要的朋友。由于本人非大神,如果有什么问题,还希望能多多指正,谢谢啦!
       如果有和我也在忙着找工作的小伙伴呢,希望咱们可以多多交流呀,一起加油吧!
       闲话不多说,咱们进入LeetCode的题目吧!
题目: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的所在数组的位置,所以要有两个for循环,那么第一个代码就出来了:

public int[] twoSum(int[] nums, int target) {
    int[] index = new int[2];
    for(int i=0;i<nums.length-1;i++){
        for(int j=i+1;j<nums.length;j++){
            if(target ==nums[i] +nums[j]){
                index[0] = i;
                index[1] = j;
            }
        }
    }
    return index;
}

       这道题这样写在LeetCode上也可以编译通过,并且Accepted,但可以看到它的运行时间Runtime: 444 ms,运行结果显示的是Your runtime beats 30.62% of java coders,也就是说其实这道题还有其他解,并且比当前运行时间要小很多,那么我们分析一下,上面的代码总体时间复杂度其实是O(n2),这样的时间复杂度是很可怕的,不到玩不得以还是不要写出这种时间复杂度的代码,而且面试官看到这种代码,我想只有被拒的可能性了!那么有没有更优的解决办法呢?
       其实用过Map的小伙伴,可以很快想到可以用map,因为map的查询操作的时间复杂度是O(1),在这种可以用HashMap(这也是很多互联网公司常考的数据结构),代价是用空间换取时间。其实很难说是不是最优解,不过从运行时间上来说,比第一种较为暴力的遍历要好很多。
       如果用HashMap的话,key很容易想到用nums[]数组中的值,那么value值呢?因为此题要求返回的是index,因此可以让value存储index,请看下面这段代码:(本段代码实看了LeetCode上的部分代码再写的)

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(target - nums[i])) 
                return new int[] {map.get(target - nums[i]) + 1, i + 1};
            else map.put(nums[i], i);
            }
        return null;
    }
}

       LeetCode显示Accepted,查看运行时间,Runtime: 332 ms,Your runtime beats 92.04% of java coders.这样的代码就很优秀了!今天就先到这,明天咱们接着聊吧!~_~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章