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

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

leetcode1. Two Sum

2019-11-10 17:09:29
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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].

解法一

兩個(gè)循環(huán)遍歷,取兩個(gè)序號(hào)

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存放數(shù)值,value存放出現(xiàn)的位置。從前到后進(jìn)行遍歷,將target值減去當(dāng)前的值,看是否存在map中,

若存在map中則取出相應(yīng)的標(biāo)號(hào),退出。

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


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 高邮市| 土默特右旗| 呼玛县| 海城市| 昭通市| 泽州县| 昭觉县| 白朗县| 霍州市| 肥东县| 准格尔旗| 岳阳市| 永平县| 济宁市| 宜阳县| 柳江县| 泰兴市| 新兴县| 健康| 唐海县| 阳朔县| 宾川县| 周至县| 天气| 尚志市| 敦化市| 清流县| 榆社县| 东辽县| 丹凤县| 连城县| 海口市| 毕节市| 罗平县| 宁夏| 英山县| 岑溪市| 韶山市| 遵义县| 桃江县| 邵阳县|