第一题 两数之和(Map功能描述待完成)

发布时间 2023-09-18 21:18:38作者: messing

先是我的暴力解法(有点菜):

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         for(int i = 0; i < nums.length-1; i++)
 4         {
 5             for(int j = i + 1; j < nums.length; j++)
 6             {
 7                 if(nums[i] + nums[j] == target)
 8                 {
 9                     return new int[] {i,j};
10                 }
11             }
12         }
13         return new int[0];
14     }
15 }

 

此处对应力扣哈希答法:

https://leetcode.cn/problems/two-sum/solutions/434597/liang-shu-zhi-he-by-leetcode-solution/
 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         //Map<>中的两个数据类型分别对应哈希表中键和值的数据类型
 4         Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
 5         for (int i = 0; i < nums.length; ++i) {
 6             if (hashtable.containsKey(target - nums[i])) {
 7                 return new int[]{hashtable.get(target - nums[i]), i};
 8             }
 9             hashtable.put(nums[i], i);
10         }
11         return new int[0];
12     }
13 }

我之前是真的不会哈希表

Java Map的简单应用:

 Map<Integer, Integer> map = new HashMap<Integer, Integer>();

map.put(key,value):将某对数据存入哈希表,其中前者表示键,后者表示值

map.get(key):读入某一键,返回对应的值

map.containskey(key):判断是否有对应的键,如果有返回true,否则返回fause

map.containskey(value):判断是否有对应的值,如果有返回true,否则返回fause

代码展示:

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 
 4 public class Main {
 5     public static void main (String[] args) {
 6         Map<Integer,String> map = new HashMap<Integer,String>();
 7         map.put(1,"a");
 8         map.put(2,"b");
 9         map.put(3,"c");
10         map.put(4,"d");
11         String num1;
12         num1 = map.get(1);
13         System.out.println(num1);
14         System.out.println(map.containsKey(1));
15         System.out.println(map.containsKey(6));
16     }
17 }

运行结果:

 

(其他功能懒一把,以后补上)