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

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

leetcode1. Two Sum

2019-11-10 16:57:31
字體:
供稿:網(wǎng)友

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

解法一

兩次循環(huán)遍歷,找到相應(yīng)序號

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: 58 ms

解法二

利用hashmap,key存放數(shù)值,value存放出現(xiàn)的位置。從前到后進行遍歷,將target值減去當(dāng)前的值,看是否存在map中,

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

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: 8 ms


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 塔城市| 东乌| 旌德县| 平武县| 沾化县| 溆浦县| 娱乐| 祁东县| 扶余县| 沙坪坝区| 南宫市| 晋州市| 乌鲁木齐市| 东乌珠穆沁旗| 绥芬河市| 昌乐县| 乌兰察布市| 竹溪县| 钟祥市| 抚宁县| 彰化县| 琼结县| 建平县| 灵川县| 巢湖市| 永善县| 科技| 祁阳县| 南木林县| 石首市| 伊春市| 桐庐县| 绩溪县| 扎赉特旗| 张家港市| 台安县| 凤凰县| 柏乡县| 兴城市| 新乐市| 高台县|