leetcode algorithms: two sum

来源:互联网 发布:杭州网络 编辑:程序博客网 时间:2024/06/15 01:29
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

下面是我的解法(感觉leetcode没有acm oj要求那么那么高),其中注释代码为普通解法。

package com.my.own;import java.util.Hashtable;import java.util.Scanner;public class Solution {    public static int[] twoSum(int[] nums, int target) {        int[] temp = new int[2];//        for(int i=0; i<nums.length -1; i++){//        for(int j=i+1; j<nums.length; j++){//        if(nums[i] + nums[j] == target){//        temp[0] = i;//        temp[1] = j;//        break;//        }//        }//        }       Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();        for(int i=0; i<nums.length; i++){        ht.put(nums[i] , i);        }                for(int i=0; i<nums.length; i++){        if(ht.containsKey(target - nums[i])){        temp[0] = i + 1;        if(ht.get(target - nums[i]) != i){        temp[1] = ht.get(target - nums[i]) + 1;            break;        }        }        }            return temp;    }        public static void  main(String[] args){    Scanner in = new Scanner(System.in);    System.out.printf("please input string split by space......\n");    String s = in.nextLine();    String[] temp = s.split(" ");    int[] array = new int[temp.length];    for(int i=0; i<temp.length; i++){    array[i] = Integer.parseInt(temp[i]);    }        System.out.printf("please input target.......\n");    int target = in.nextInt();        int[] result = twoSum(array, target);    System.out.printf("result is:index1=%d, index2=%d\n", result[0], result[1]);    }}


0 0