【力扣LeetCode】java算法刷题大全第2题之寻找数组的目标下标

该博客主要介绍了如何在Java中解决LeetCode第2题,即找到数组中两个数相加等于目标值的它们的下标。例如,给定数组[1, 5, 2, 7, 9, 8]和目标值15,输出下标为3和5的元素。通过代码实现,得出解决方案。" 79339306,6995414,STM32 Systick系统定时器详解与配置实践,"['STM32开发', '嵌入式系统', '时钟源', '系统定时器']
摘要由CSDN通过智能技术生成

一、给定一个数组,找出数组中的两个数字相加之后等于目标值的俩数字下标

示例: 数组[1, 5, 2, 7, 9, 8],目标值:15,

输出下标: 3,5

package com.example.dzx.datastrctet;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 500007
 * @ClassName:
 * @Description: 给定一个数组,找出数组中的两个数字相加之后等于目标值的俩数字下标
 * 示例: 数组[1, 5, 2, 7, 9, 8],目标值:15,输出下标,3,5
 * @date 2022年04月22日 15:07:05
 */
public class TwoSum {

    /**
     * 双层for循环:暴力穷举法
     *
     * @param xx
     * @param target
     * @return
     */
    public int[] twoSum1(int[] xx, int target) {
        int[] indexs = new int[2];
        for (int i = 0; i < xx.length; i++) {
            for (int j = i + 1; j < xx.length; j++) {
                if (xx[i] + xx[j] == target) {
                    indexs[0] = i;
                    indexs[1] = j;
                }
            }
        }
        return indexs;
    }

    /**
     * 利用map缓存倒推计算法
     *
     * @param xx
     * @param target
     * @return
     */
    public int[] twoSum2(int[] xx, int target) {
        //key为元素值,value为元素下标
        int[] indexs = new int[2];
        Map<Integer, Integer> map = new HashMap<>(xx.length);
        for (int i = 0; i < xx.length; i++) {
            int anotherValue = target - xx[i];
            Integer anotherIndex = map.get(anotherValue);
            if (anotherIndex == null) {
                map.put(xx[i], i);
            } else {
                indexs[0] = anotherIndex;
                indexs[1] = i;
                break;
            }
        }
        return indexs;
    }


    public static void main(String[] args) {
        //给定一个数组,找出数组中的两个数字相加之后等于目标值的俩数字下标
        int[] xx = new int[]{1, 5, 2, 7, 9, 8};
        int target = 15;
        System.out.println(Arrays.toString(new TwoSum().twoSum1(xx, target)));
        System.out.println(Arrays.toString(new TwoSum().twoSum2(xx, target)));
    }
}

运行代码,输出如下:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小米吃辣椒2022

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

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

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

打赏作者

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

抵扣说明:

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

余额充值