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

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

leetcode 1 TwoSum

2019-11-08 02:39:50
字體:
來源:轉載
供稿:網友

leetcode 1. TwoSum

問題描述:

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

思路

方法1:

一種相對直接的方法,分兩層遍歷數組,如果兩個數的結果等于目標數則返回,時間復雜度為O(n^2)

代碼:

/** * Created by Henry on 2017/1/16. */public class TwoSum { public static void main(String[] ages){ int[] nums = {1,3,5,9}; int target = 8; int [] results = new int[2]; results = twoSum(nums, target); System.out.PRintln(results[0]); System.out.println(results[1]); } public static int[] twoSum(int[] nums, int target){ int[] results = new int[2]; int flag = 0; for(int i=0;i < nums.length; i++){ if(flag != 0) break; for(int j = i+1; j < nums.length; j++){ if(nums[i]+nums[j] == target){ results[0] = i; results[1] = j; flag = 1; break; } } } return results; }}

方法2:

希望能夠通過一次遍歷求得結果。引入Map數據結構,每次遍歷時以數組的數字為key,索引為value放入map(這種map在考察數組的算法題中比較常見)中,每次遍歷數字前首先判斷目標數字與要遍歷的數字的差是否在map中,如果不在則繼續遍歷,否則在map中則找到了第二個數字,將這個數字的索引放入結果數組中,再以目標數字與這個數字的差為key得到第一數字的索引位置并放入結果數組中。這種方法的時間復雜度為O(n),時間復雜度降低了,但是引入了map數據結構,以犧牲空間為代價來降低運行時間。

代碼:

import java.util.HashMap;import java.util.Map;/** * Created by Henry on 2017/2/18. */public class TwoSum2 { public static void main(String[] args){ int [] nums = {1, 3, 5, 9}; int [] results = new int[2]; int target = 8; TwoSum2 twosum2 = new TwoSum2(); results = twosum2.twoSum(nums, target); System.out.println(results[0]+","+results[1]); } public int[] twoSum(int[] nums, int target){ int[] results = new int[2]; Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i = 0; i < nums.length; i++){ if(map.containsKey(target - nums[i])){ results[1] = i; results[0] = map.get(target-nums[i]); return results; } map.put(nums[i], i); } return results; }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 哈巴河县| 商河县| 韶关市| 老河口市| 蒙城县| 新余市| 九龙城区| 肥西县| 绍兴市| 西峡县| 正阳县| 天全县| 阿拉善左旗| 廉江市| 三台县| 黎川县| 舟山市| 临沧市| 信阳市| 漳州市| 辽宁省| 鄂托克前旗| 景德镇市| 白沙| 沭阳县| 景泰县| 上栗县| 汕尾市| 汶上县| 昌邑市| 华安县| 马公市| 凭祥市| 通山县| 嫩江县| 浮山县| 麦盖提县| 桐柏县| 吉安市| 金阳县| 徐闻县|