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

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

leetcode1. Two Sum

2019-11-10 17:01:55
字體:
來源:轉載
供稿:網友

1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example: Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

解法一

兩個循環遍歷,取兩個序號

public class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; for(int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { result[0] = i; result[1] = j; return result; } } } return result; }}

Runtime: 44 ms

解法二

利用hashmap,key存放數值,value存放出現的位置。從前到后進行遍歷,將target值減去當前的值,看是否存在map中,

若存在map中則取出相應的標號,退出。

public class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++) { int num = target - nums[i]; if (map.containsKey(num)) { result[0] = map.get(num); result[1] = i; return result; } map.put(nums[i], i); } return result; }}

Runtime: 12 ms


上一篇:PCI驅動編程基本框架

下一篇:day19

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 枣阳市| 福安市| 宣恩县| 桑日县| 阿鲁科尔沁旗| 潜山县| 阿图什市| 兴城市| 桂东县| 甘肃省| 沈阳市| 中超| 广水市| 泽州县| 曲松县| 遂平县| 乌审旗| 汉阴县| 沂水县| 寿阳县| 大田县| 财经| 万载县| 镇安县| 锡林郭勒盟| 双牌县| 合水县| 乌苏市| 新疆| 黄陵县| 太仆寺旗| 特克斯县| 益阳市| 乌海市| 枝江市| 东城区| 湘阴县| 巴塘县| 军事| 新巴尔虎右旗| 龙川县|