zoukankan      html  css  js  c++  java
  • HashMap 专题

    hashmap map key and value for highly efficient lookup.

    hashmap search used binary tree O(log2)

    main methods

    int size();

    hashmap.put(key,value);

    Value get(key);

    boolean containsKey(key);

    boolean containsValue(Value);

    remove(key)

    leetcode:

    1.Two Sum

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9

    Output: index1=1, index2=2

    solution:

    Key:value

    Value:indice

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

     

    Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
        if(s.length()<=1){
                return s.length();
            }
        HashMap<Character,Integer> map=new HashMap<Character,Integer>();
        int max=0;
        int current=0;
        char[] c=s.toCharArray();
        for(int i=0;i<c.length;i++){
            char v=c[i];
            if(map.containsKey(v)&&map.get(v)>=current){
                current=map.get(v)+1;
            }
            else{
                max=Math.max(max,i-current+1);
            }
            map.put(v,i);
        }
        return max;
        }
    }
  • 相关阅读:
    超强视频分割/剪辑软件-Ultra Video Splitter绿色便携版
    超强视频分割/剪辑软件-Ultra Video Splitter绿色便携版
    ASP.NET做WEB开发的工具选择
    ASP.NET做WEB开发的工具选择
    C#中的局部类型
    OpenCV2:幼儿园篇 第四章 访问图像
    OpenCV2:幼儿园篇 第三章 导出图像
    OpenCV2:幼儿园篇 第二章 读取图像
    OpenCV2:幼儿园篇 第一章 创建图像并显示
    MFC隐藏在黑暗之中的大坑
  • 原文地址:https://www.cnblogs.com/joannacode/p/4584791.html
Copyright © 2011-2022 走看看