leetcode two-sum(Java)

leetcode题目

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

思路

 * 思路1:(需要两次遍历数组)
 * 1、遍历数组,把每个值作为key, 索引+1 作为value
 * 2、再次遍历数组,查看map中是否有target-curNum作为key的项,有的话则找到目标值
 * 思路2:(一次遍历数组即可)
 * 1、遍历数组,如果map包含key为curNum的值,则找到目标值。否则把target-curNum作为key, 
 *    索引作为value放入map

代码

package com.my.test.leetcode.array;

import java.util.HashMap;
import java.util.Map;

/**
 * 题目:
 * 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 TwoSum
{
    /**
     * 思路:(需要两次遍历数组)
     * 1、遍历数组,把每个值作为key, 索引+1 作为value
     * 2、再次遍历数组,查看map中是否有target-curNum作为key的项,有的话则找到目标值
     */
    public int[] twoSum(int[] numbers, int target) {
        if (numbers == null || numbers.length <= 1) {
            return null;
        }
        
        // 缓存所有值到hash表中,取值时间复杂度o(1)
        Map cache = new HashMap<>();
        int len = numbers.length;
        for (int i=0; i cache = new HashMap<>();
        int[] ret = new int[2];
        
        int len = numbers.length;
        for (int i=0; i

你可能感兴趣的:(Leetcode题目,two-sum,leetcode,牛客,Java,哈希)