leetcode 1

leetcode 1 two sum

给定一个数组和目标数,若数组中有两个数相加等于目标数,给出这两个数的下标

方法暴力搜索

最简单直观的方法,但是耗时长。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        boolean k=false;
        int[] a=new int[2];
        for(int i=0;i<nums.length;i++){
            for(int j=0;j<nums.length;j++){
                if(nums[i]+nums[j]==target&&i!=j){
                    a[0]=i;
                    a[1]=j;
                    k=true;
                    break;
                }
            }
            if(k){
                break;  
            }  
        }
        return a;
    }
}

使用map,将数组中的数加入map中,边加入,边判断目标数减加入的数是否在map中。大幅降低了时间复杂度。

class Solution {
    public int[] twoSum(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;
    }
}

也有先根据目标数大小,缩小数组中符合的数的范围,再进行搜索的方法,比较费脑子。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值