1. 程式人生 > >兩數之和

兩數之和

map() targe port twosum next pri 們的 rgs 一個數

問題描述

給定一個數組
number\(_i\),找到兩個數,使得他們的和為一個給定的數值 target。
其中:
number[index\(_1\)]+number[index\(_2\)]==target。
註意:index\(_1\)必須小於index\(_2\)且不能為0。
假設每一組輸入只有唯一的一組解。
例如:
對於數組[2,7,11,15] 和 target=18,index\(_1\)的值為 2,index\(_2\)的值為 3。

輸入格式

第一行輸入一個整數 n (1≤n≤500),接下來的兩行分別輸入 n 個整數組成的
數組 number\(_i\) (0 ≤ number\(_i\)

≤1000) 和一個整數 target (0 ≤ target ≤ 1000)。

輸出格式

輸出一行由空格分隔的兩個整數 index\(_1\) 和 index\(_2\)
註意,下標從 1 開始。

代碼

package javaexam;

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

public class TwoSum
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        
        int
n = input.nextInt(); int target; int[] num = new int[n]; HashMap map = new HashMap(); for(int i = 0; i < n; ++i) { num[i] = input.nextInt(); } target = input.nextInt(); for(int i = 0; i < n; ++i) { if
(map.containsKey(target - num[i])) { // HashMap 搜索時間復雜度為O(1) System.out.printf("%d %d", map.get(target - num[i]), i + 1); // printf格式化輸出函數 break; } map.put(num[i], i + 1); } } }

樣例測試

4
2 7 11 15
18
2 3

兩數之和