码迷,mamicode.com
首页 > 其他好文 > 详细

1. Two Sum - LeetCode

时间:2018-06-17 01:06:00      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:find   pre   problems   return   ==   problem   复杂度   hash   nta   

Question

1. Two Sum

技术分享图片

Solution

思路很简单这里就不说了,下面贴了不同的几个Java实现的时间与其他算法实现的时间的比较

这个是LeetCode的第一道题,也是我刷的第一道,刚一开始的Java实现

public int[] twoSum(int[] nums, int target) {
    boolean find = false;
    int targeti = -1, targetj = -1;
    for (int i = 0; i < nums.length; i++) {
        for (int j = 0; j < nums.length; j++) {
            if (i == j) {
                continue;
            }
            if (nums[i] + nums[j] == target) {
                targeti = i;
                targetj = j;
                find = true;
                break;
            }
        }
        if (find) {
            break;
        }
    }
    return new int[]{targeti, targetj};
}

技术分享图片

稍微改进一下

public int[] twoSum(int[] nums, int target) {
    boolean find = false;
    int targeti = -1, targetj = -1;
    for (int i = 0; i < nums.length - 1; i++) {
        for (int j = i + 1; j < nums.length; j++) {

            if (nums[i] + nums[j] == target) {
                targeti = i;
                targetj = j;
                find = true;
                break;
            }
        }
        if (find) {
            break;
        }
    }
    return new int[]{targeti, targetj};
}

技术分享图片

下面这个版本是在讨论中看到的O(1)时间复杂度

public int[] twoSum3(int[] nums, int target) {
    int[] result = new int[2];
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(target - nums[i])) {
            result[1] = i;
            result[0] = map.get(target - nums[i]);
            return result;
        }
        map.put(nums[i], i);
    }
    return result;
}

技术分享图片

1. Two Sum - LeetCode

标签:find   pre   problems   return   ==   problem   复杂度   hash   nta   

原文地址:https://www.cnblogs.com/okokabcd/p/9191871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!