Two Sum

来源:互联网 发布:微信电子相册软件 编辑:程序博客网 时间:2024/05/24 01:51
    看完题目的时候,就理所当然的想到了平时最常用的方法:双重循环。
public int[] twoSum(int[] numbers, int target) {        int[] result = new int[2];                boolean isFound = false;for(int i = 0; i < numbers.length && isFound == false; i ++){        int first = numbers[i];        for(int j = i; j < numbers.length; j ++){        int second = numbers[j];        if(first + second == target){        result[0] = i;        result[1] = j;        isFound = true;        break;        }        }                }        return result;    }

但是提交代码之后显示超时。所以采用HashMap降低时间复杂度

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


0 0
原创粉丝点击