【LeetCode】001Two Sum

1. Two Sum

https://leetcode.com/problems/two-sum/

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
        for(int i=0;i<nums.length;i++){
            m.put(nums[i],i);
        }
        for(int i=0;i<nums.length;i++){
            int temp = target - nums[i];
            if(m.containsKey(temp) && m.get(temp)!=i){
                res[0]=i;
                res[1]=m.get(temp);
                break;
            }
        }
        return res;
    }
}

HashMap

import java.util.*;
 
public class Str {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Map map = new HashMap();
        //成对放入多个key-value对
        map.put("大学数学",109 );
        map.put("大学物理",10);
        map.put("算法导论",79);
        map.put("数据结构", 99);
        //放入重复的key时,新的value会覆盖原有的value。
        //如果新的value覆盖了原有的value,该方法返回被覆盖的value值
        System.out.println(map.put("操作系统",99));
        System.out.println(map.put("大学物理",99));
        System.out.println(map);
        System.out.println("是否包含值为 操作系统 key:"+map.containsKey("操作系统"));
        System.out.println("是否包含值为 99 value:"+map.containsValue(99));
        //获取map集合的所有key组成的集合,通过遍历key来实现遍历所有的key-value对
        for(Object key : map.keySet()) {
            System.out.println(key + "--->"+map.get(key));
        }
        map.remove("大学物理");
        System.out.println(map);
    }
 
}
null
10
{大学物理=99, 操作系统=99, 算法导论=79, 数据结构=99, 大学数学=109}
是否包含值为 操作系统 key:true
是否包含值为 99 value:true
大学物理--->99
操作系统--->99
算法导论--->79
数据结构--->99
大学数学--->109
{操作系统=99, 算法导论=79, 数据结构=99, 大学数学=109}

1、containsKey(Object key)方法,返回值为boolean,用于判断当前hashmap中是否包含key对应的key-value

2、containsValue(Object value)方法,返回值为boolean,用于判断当前hashmap中是否包含value对应的key-value

3、HashMap的遍历包含多种方法,此处不是最高效的。

posted @ 2021-09-06 17:26  Clancy_gang  阅读(29)  评论(0编辑  收藏  举报