Given an array of integers, return indices of the two numbers such that they add up to a specific ta

问题是要从数组中找到两个数据,使得两数之和等于目标值,输出该两数的下标(从0开始)

方法一:

public static int[] twoSum_2(int[] num,int target ) {
		int low ,high;
		int temp;
		for(int i = 0; i< num.length; i++){
			low = i;
			temp = target- num[i];
			for(int j =i+1; j< num.length; j++){
				if(temp == num[j]){
					high = j;
					return new int[]{low,high};
				}
			}
			
			
		}
		return null;
	}

 方法二:用hashmap减少查找时间

import java.util.HashMap;
import java.util.Scanner;

import javax.swing.text.NumberFormatter;


public class Solution {
	public static int[] twoSum(int[] num,int target ) {
		final HashMap<Integer,Integer> myMap = new HashMap<Integer, Integer>();
		//int []result = new int[2];
		for (int i = 0; i < num.length; i++) {
			myMap.put( num[i],i);
			}
		for (int i = 0; i < num.length; i++) {
			int v =  myMap.get( target - num[i]);
				if (v != 0 && v > i) {
					return new int[]{i,v};
				}
		}
		return null;
		
		
	}
	public static void main(String[] args) {
		int num[] = new int[]{2,7,11,15};
		Scanner scanner = new Scanner(System.in);
		int target = scanner.nextInt();
		int []array = twoSum(num, target);
		System.out.print("[");
		for (int i = 0; i < array.length; i++) {	
			System.out.print(array[i]+" ");	
			//System.out.print("");
		}
		System.out.print("]");		
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值