国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

1. Two Sum

2019-11-14 23:48:19
字體:
來源:轉載
供稿:網友
1. 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=9Output:index1=1, index2=2

鏈接:http://leetcode.com/PRoblems/two-sum/

題解:

使用HashMap,一次遍歷數組,Time Complexity - O(n),Space Complexity - O(n)

public class Solution {    public int[] twoSum(int[] numbers, int target) {        int result[] = {-1, -1};        if(numbers == null || numbers.length == 0)            return result;        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();        for(int i = 0; i < numbers.length; i++){            if(!map.containsKey(target - numbers[i]))                map.put(numbers[i], i);            else{                result[0] = map.get(target - numbers[i]) + 1;                result[1] = i + 1;                break;           }            }        return result;    }}

Reference:

http://m.survivalescaperooms.com/springfor/p/3859618.html


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 苏州市| 内黄县| 招远市| 濮阳县| 华安县| 土默特右旗| 察哈| 勐海县| 英德市| 潞西市| 安西县| 浦城县| 兰溪市| 封丘县| 灌云县| 桦南县| 金寨县| 镇原县| 金阳县| 德清县| 军事| 同仁县| 东莞市| 乡城县| 荃湾区| 哈尔滨市| 中卫市| 辽源市| 武强县| 调兵山市| 沁阳市| 赞皇县| 香港| 丽江市| 志丹县| 眉山市| 谢通门县| 林甸县| 内乡县| 蓝山县| 高要市|