leetcode 1: 找出两个数相加等于给定数 two sum
問題描述
對(duì)于一個(gè)給定的數(shù)組,找出2個(gè)數(shù),它們滿足2個(gè)數(shù)的和等于一個(gè)特定的數(shù),返回這兩個(gè)數(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)即可.
? ?使用暴力,一般效率都會(huì)比較慢,但易于理解.? ??
?
思路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ù)組下標(biāo)map.put(arr[i], i);}}System.out.println(Arrays.toString(resultArr));} }?
總結(jié)
以上是生活随笔為你收集整理的leetcode 1: 找出两个数相加等于给定数 two sum的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ThreadLocal原理与使用
- 下一篇: LeetCode 2 两数相加(链表)