leetcode-1-两数之和
生活随笔
收集整理的這篇文章主要介紹了
leetcode-1-两数之和
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目:
1、暴力解法
1 package com.example.demo; 2 3 public class TestLeetCode { 4 public static void main(String[] args) { 5 TestLeetCode t = new TestLeetCode(); 6 int[] i = {2, 7, 11, 15}; 7 int target = 17; 8 int[] o = t.twoSum(i, target); 9 10 for (int i1 : o) { 11 System.out.println(i1); 12 } 13 14 } 15 16 /** 17 * 暴力解法就是將所有的數(shù)據(jù)都算一遍,和目標(biāo)值比較,同澤返回i,j索引,否則返回null即可(遍歷冒泡) 題目要求返回的是索引數(shù)據(jù),并不是值數(shù)組 18 * @param nums 19 * @param target 20 * @return 21 */ 22 public int[] twoSum(int[] nums, int target) { 23 24 for (int i = 0; i < nums.length; i++) { 25 //j = i + 1 ,不和自身相加 26 for (int j = i + 1; j < nums.length; j++) { 27 if ((nums[j] + nums[i]) == target) { 28 return new int[]{i, j}; 29 } 30 } 31 } 32 return null; 33 } 34 }?
2、使用map數(shù)據(jù)結(jié)構(gòu)
package com.example.demo;import java.util.HashMap; import java.util.Map;public class TestLeetCode {public static void main(String[] args) {TestLeetCode t = new TestLeetCode();int[] i = {2, 7, 11, 15};int target = 17;int[] o = t.twoSum(i, target);for (int i1 : o) {System.out.println(i1);}}/*** 利用hash數(shù)據(jù)結(jié)構(gòu),先將數(shù)組中的value作map的key,index作map的value,保存起來,然后遍歷數(shù)組,* 如果存在一個(gè)結(jié)果等于target-nums[i]時(shí),此時(shí)這個(gè)值和nums[i]就是目標(biāo)值,再通過map.get()來獲取到對(duì)應(yīng)的索引** @param nums* @param target* @return*/public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {map.put(nums[i], i);}for (int i = 0; i < nums.length; i++) {int index_value = target - nums[i];if (map.containsKey(index_value) && nums[i] != index_value) {return new int[]{i, map.get(index_value)};}}return null;} }?
修改:
package com.example.demo;import java.util.HashMap; import java.util.Map;public class TestLeetCode {public static void main(String[] args) {TestLeetCode t = new TestLeetCode();int[] i = {2, 7, 11, 15};int target = 17;int[] o = t.twoSum(i, target);for (int i1 : o) {System.out.println(i1);}}/*** 利用hash數(shù)據(jù)結(jié)構(gòu),一次遍歷,在遍歷的時(shí)候判斷是否存在,不存在則將當(dāng)前的值放到map里,以便之后調(diào)用** @param nums* @param target* @return*/public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {int index_value = target - nums[i];if (map.containsKey(index_value) && nums[i] != index_value) {//這塊換了位置,是因?yàn)閙ap里邊放的都是比當(dāng)前索引小的值return new int[]{map.get(index_value), i};}map.put(nums[i], i);}return null;} }?
參考:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/
總結(jié)
以上是生活随笔為你收集整理的leetcode-1-两数之和的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mybatis默认的数据源连接池(Poo
- 下一篇: leetcode-2-两数相加