当前位置:编程学习 > JAVA >>

Two Sum @LeetCode

 
package Level2;  
  
import java.util.HashMap;  
import java.util.Hashtable;  
  
/** 
 * Two Sum 
 *  
 * 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 
 */  
public class S1 {  
  
    public static void main(String[] args) {  
        Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();  
        System.out.println(ht.get(22));  
    }  
  
    public int[] twoSum(int[] numbers, int target) {  
        // 放值和数组下标  
        Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();  
        int[] ret = new int[2];  
          
        for(int i=0; i<numbers.length; i++){  
            // 对每一个数边放边查找  
            if(ht.get(target-numbers[i]) != null){  
                ret[0] = ht.get(target-numbers[i]) + 1;  
                ret[1] = i+1;  
            }else{  
                ht.put(numbers[i], i);  
            }  
        }  
          
        return ret;  
    }  
}  

 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,