求两数之和

问题:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

很简单:

public class Test04 {
    public static void main(String[] args) {
        Integer[] a = {1, 2, 3, 4, 5, 6};
        Integer[]b;
        b= sum(a,7);
        System.out.println();
        for (int i = 0; i < b.length; i++) {
            System.out.println(b[i]);
        }
    }
    public static Integer[] sum(Integer[] arr, Integer target) {
        Integer[] tarNum = new Integer[arr.length];
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            if (i + 1 < arr.length) {
                for (int j = i + 1; j < arr.length; j++) {
                    if (arr[i] + arr[j] == target) {
                        tarNum[count] = i;
                        count++;
                        tarNum[count] = j;
                        count++;
                    }
                }
            }
        }
        return tarNum;
    }
}

哈希表算法,O(n)

public class Test16 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int[] numsResult =  twoSum(nums, 9);
        for (int i : numsResult) {
            System.out.println(i);

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

我要刷100道算法题,第4道!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

only-qi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值