1. Two Sum

1. Two SumGiven an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.


翻译:给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。

基础解法 O(n^2)

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

  • 两个for循环,这种方法最坏情景是最后两位相加=target,只看内循环,第一位到第最后一位分别访问了....(n-1) 次,复杂度达到了O(n^2),速度不尽人意

进阶解法 O(lgn)

    public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int result[] = new int[2];
        for (int i = 0; i < nums.length; i++){
            int num = target - nums[i];
            if(map.containsKey(num)){
                result[0] = map.get(num);
                result[1] = i;
                return result;
            }
            map.put(nums[i], i);
        }
        return result;
    }
JDK1.7的hashmap 极端情况下,可能只有单个链表,效率依然不高,1.8加入了红黑树,最差情况下高度不超过最低高度的2倍




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值