麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

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

leetcode1. Two Sum

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

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

解法一

兩次循環遍歷,找到相應序號

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存放數值,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: 8 ms


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 亚洲国产精品久久久久婷婷老年 | 免费看国产视频 | 精品中文字幕在线观看 | 欧美日韩视频在线播放 | 久久国产成人精品国产成人亚洲 | 久久视频精品 | 亚洲精品久久久久久 | 久久不雅视频 | 国产免费观看电影网站 | 亚洲成人免费视频在线 | 免费嗨片首页中文字幕 | 久久久三区 | 92看片淫黄大片欧美看国产片 | 成年人性视频 | 国产91久久久久久 | 久久精品久久精品国产大片 | 在线看一区二区三区 | 中文字幕22页 | av免费在线不卡 | 狠狠干91| 香蕉成人在线视频 | 免费国产一级淫片 | 精品国产一区二区三区四区在线 | 国产午夜精品一区二区三区嫩草 | 精品一区二区三区免费毛片爱 | 久草导航 | 日本不卡一区二区三区在线观看 | 一级做a爱片性色毛片高清 国产精品色在线网站 | 久在线草| 日本精品久久久久久草草 | 中国国语毛片免费观看视频 | 成人午夜免费福利 | 成人做爽爽爽爽免费国产软件 | 久久精品久久精品久久精品 | 国产人成免费爽爽爽视频 | 男男羞羞视频网站国产 | 视频一区二区不卡 | a一级黄色大片 | 亚洲精品久久久久www | 久久久久久久久日本理论电影 | 午夜色片 |