Two Sum

来源:互联网 发布:大数据 保险 客户画像 编辑:程序博客网 时间:2024/06/07 06:11
</pre><pre name="code" class="html">  public static int[] twoSum(int[] nums, int target) {        for(int i=0; i< nums.length;i++){            for(int j=i; j<nums.length; j++){                if(nums[i]+nums[j]== target){                    int index[]=new int[2];                    index[0]=i+1;                    index[1]=j+1;                    return index;                }else{                    j++;                }            }        }        return null;    }
这是我自己写的
</pre><pre name="code" class="html">

O(n2) runtime, O(1) space – Brute force:


网上查了优化的方法:

O(n) runtime, O(n) space – Hash table:


public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] res = new int[2];        res[0] = -1;        res[1] = -1;        final HashMap<Integer, Integer> h = new HashMap<Integer, Integer>();        for (int i = 0; i < nums.length; i++) {            if (h.containsKey(target - nums[i])) {                int index = h.get(target-nums[i])+1;                res[0] = Math.min(i+1, index);                res[1] = Math.max(i+1, index);            }            h.put(nums[i], i);        }        return res;    }}


                                             
0 0
原创粉丝点击