日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode 1: 找出两个数相加等于给定数 two sum

發(fā)布時間:2025/6/15 编程问答 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode 1: 找出两个数相加等于给定数 two sum 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

問題描述

對于一個給定的數(shù)組,找出2個數(shù),它們滿足2個數(shù)的和等于一個特定的數(shù),返回這兩個數(shù)的索引。(從1開始)
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target,
where index1 must be less than index2. Please note that your returned answers (both index1 and index2)
are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

思路1:使用雙指針暴力破解

? ?使用雙指針,循環(huán)即可.

? ?使用暴力,一般效率都會比較慢,但易于理解.? ??

?

思路2:使用hash表

import java.util.Arrays; import java.util.HashMap;public class TwoSum {public static void main(String[] args) {int arr[] = {3,2,5,7,11};int[] resultArr = new int[2];HashMap map = new HashMap();for(int i=0; i<arr.length; i++){int result = 9 - arr[i];if(null != map.get(result)){resultArr[0] = (int)map.get(result);resultArr[1] = i;break;}else{// 保存數(shù)組值,以及數(shù)組下標map.put(arr[i], i);}}System.out.println(Arrays.toString(resultArr));} }

?

總結(jié)

以上是生活随笔為你收集整理的leetcode 1: 找出两个数相加等于给定数 two sum的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。