Leetcode哈希表题(java作答)

目录

136.只出现一次的数字

202.快乐数

219.存在重复元素II

205.同构字符串

242.有效的字母异位词

299.猜数字游戏

290.单词规律

500.键盘行

690.员工的重要性

771.宝石与石头


136.只出现一次的数字

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,1]
输出: 1
示例 2:

输入: [4,1,2,1,2]
输出: 4

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number

class Solution {
    public int singleNumber(int[] nums) {
        HashSet<Integer> hs1=new HashSet<Integer>();
        for(int i:nums){
            if(hs1.contains(i)){
                hs1.remove(i);
            }else{
                hs1.add(i);
            }
        }
        Iterator<Integer> it=hs1.iterator();
        return (int)it.next();
    }
}

202.快乐数

编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为  1,那么这个数就是快乐数。

如果 n 是快乐数就返回 True ;不是,则返回 False 。

示例:

输入:19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/happy-number

class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> hset1=new HashSet<Integer>();
        while(true){
            if(n==1){
                break;
            }
            if(hset1.contains(n)){
                return false;
            }else{
                hset1.add(n);
                n=sunOfsquares(n);
            }
            
        }
        return true;
    }
    public int sunOfsquares(int n){
        int sum = 0;
        while( true ){
            if( n==0 ){
                break;
            }
            sum += Math.pow( n%10 , 2 );
            n /=10;
        }
        return sum;
    }
}

219.存在重复元素II

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 绝对值 至多为 k。

 

示例 1:

输入: nums = [1,2,3,1], k = 3
输出: true
示例 2:

输入: nums = [1,0,1,1], k = 1
输出: true
示例 3:

输入: nums = [1,2,3,1,2,3], k = 2
输出: false

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contains-duplicate-ii

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(k==0){
            return false;
        }
        HashSet<Integer> hset1=new HashSet<Integer>();
        for(int i=0;i<nums.length;i++){
            if(hset1.contains(nums[i])){
                return true;
            }else{
                if(i>=k){
                    hset1.remove(nums[i-k]);
                }
                hset1.add(nums[i]);
            }
        }
        return false;
    }
}

205.同构字符串

给定两个字符串 s 和 t,判断它们是否是同构的。

如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。

所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。

示例 1:

输入: s = "egg", t = "add"
输出: true
示例 2:

输入: s = "foo", t = "bar"
输出: false
示例 3:

输入: s = "paper", t = "title"
输出: true
说明:
你可以假设 s 和 t 具有相同的长度。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/isomorphic-strings

class Solution {
    public boolean isIsomorphic(String s, String t) {
        HashMap<Character,Character> hstab1 = new HashMap<Character,Character>();
        for(int i=0;i<s.length();i++){
            char s_char=s.charAt(i);
            char t_char=t.charAt(i);
            if(!hstab1.containsKey(s_char)){
                if(hstab1.containsValue(t_char)){
                    return false;
                }
                hstab1.put(s_char,t_char);
            }else if(hstab1.get(s_char)!=t_char){
                return false;
            }
        }
        return true;
    }
}

242.有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true
示例 2:

输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-anagram

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length()){
            return false;
        }
        HashMap<Character,Integer> map_s = new HashMap<Character,Integer>();
        HashMap<Character,Integer> map_t = new HashMap<Character,Integer>();
        char sc=' ';
        char tc=' ';
        for(int i=0;i<s.length();i++){
            sc=s.charAt(i);
            tc=t.charAt(i);
            if(map_s.containsKey(sc)){
                map_s.put(sc,map_s.get(sc)+1);
            }else{
                map_s.put(sc,1);
            }
            if(map_t.containsKey(tc)){
                map_t.put(tc,map_t.get(tc)+1);
            }else{
                map_t.put(tc,1);
            }
        }
        return map_s.equals(map_t);
    }
}

299.猜数字游戏

你正在和你的朋友玩 猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给他一个提示,告诉他有多少位数字和确切位置都猜对了(称为“Bulls”, 公牛),有多少位数字猜对了但是位置不对(称为“Cows”, 奶牛)。你的朋友将会根据提示继续猜,直到猜出秘密数字。

请写出一个根据秘密数字和朋友的猜测数返回提示的函数,用 A 表示公牛,用 B 表示奶牛。

请注意秘密数字和朋友的猜测数都可能含有重复数字。

示例 1:

输入: secret = "1807", guess = "7810"

输出: "1A3B"

解释: 1 公牛和 3 奶牛。公牛是 8,奶牛是 0, 1 和 7。
示例 2:

输入: secret = "1123", guess = "0111"

输出: "1A1B"

解释: 朋友猜测数中的第一个 1 是公牛,第二个或第三个 1 可被视为奶牛。
说明: 你可以假设秘密数字和朋友的猜测数都只包含数字,并且它们的长度永远相等。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bulls-and-cows

class Solution {
    public String getHint(String secret, String guess) {
        int numsBulls=0;
        int numsCows=0;
        ArrayList<Character> lst = new ArrayList<Character>();
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i=0;i<guess.length();i++){
            if(secret.charAt(i)==guess.charAt(i)){
                numsBulls++;
            }else{
                if(map.containsKey(secret.charAt(i))){
                    map.put(secret.charAt(i),map.get(secret.charAt(i))+1);
                }else{
                    map.put(secret.charAt(i),1);
                }
                lst.add(guess.charAt(i));
            }
        }
        for(char c:lst){
            if(map.containsKey(c)){
                map.put(c,map.get(c)-1);
                numsCows++;
                if(map.get(c)==0){
                    map.remove(c);
                }
            }
        }
        return ""+numsBulls+"A"+numsCows+"B";
    }
}

290.单词规律

给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。

这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。

示例1:

输入: pattern = "abba", str = "dog cat cat dog"
输出: true
示例 2:

输入:pattern = "abba", str = "dog cat cat fish"
输出: false
示例 3:

输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false
示例 4:

输入: pattern = "abba", str = "dog dog dog dog"
输出: false
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。    

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-pattern

class Solution {
    public boolean wordPattern(String pattern, String str) {
        ArrayList<String> words = new ArrayList<String>();
        String word ="";
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)!=' '){
                word+=str.charAt(i);
            }
            if(str.charAt(i)==' '||i==str.length()-1){
                words.add(word);
                word = "";
            }
        }
        if(pattern.length()!=words.size()){
            return false;
        }
        HashMap<Character,String> map = new HashMap<Character,String>();
        for(int i=0;i<pattern.length();i++){
            if(map.containsKey(pattern.charAt(i))){
                if(!map.get(pattern.charAt(i)).equals(words.get(i))){
                    return false;
                }
            }else{
                if(map.containsValue(words.get(i))){
                    return false;
                }
                map.put(pattern.charAt(i),words.get(i));
            }
        }
        return true;
    }
}

500.键盘行

给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。

American keyboard

示例:

输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
 

注意:

你可以重复使用键盘上同一字符。
你可以假设输入的字符串将只包含字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/keyboard-row

class Solution {
    public String[] findWords(String[] words) {
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        String line1 = "QWERTYUIOPqwertyuiop";
        String line2 = "ASDFGHJKLasdfghjkl";
        String line3 = "ZXCVBNMzxcvbnm";
        String[] line = new String[]{
            line1,
            line2,
            line3
        };
        for(int i=0;i<line.length;i++){
            for(int j=0;j<line[i].length();j++){
                map.put(line[i].charAt(j),i+1);
            }
        }
        int flag=0;
        boolean flag1=true;
        ArrayList<String> ans = new ArrayList<String>();
        for(int i=0;i<words.length;i++){
            flag1=true;
            flag=map.get(words[i].charAt(0));
            for(int j=0;j<words[i].length();j++){
                if(map.get(words[i].charAt(j))!=flag){
                    flag1=false;
                    break;
                }
            }
            if(flag1){
                ans.add(words[i]);
            }
        }
        String[] ans1 = new String[ans.size()];
        int z=0;
        for(String s:ans){
            ans1[z++]=s;
        }
        return ans1;
    }
}

690.员工的重要性

给定一个保存员工信息的数据结构,它包含了员工唯一的id,重要度 和 直系下属的id。

比如,员工1是员工2的领导,员工2是员工3的领导。他们相应的重要度为15, 10, 5。那么员工1的数据结构是[1, 15, [2]],员工2的数据结构是[2, 10, [3]],员工3的数据结构是[3, 5, []]。注意虽然员工3也是员工1的一个下属,但是由于并不是直系下属,因此没有体现在员工1的数据结构中。

现在输入一个公司的所有员工信息,以及单个员工id,返回这个员工和他所有下属的重要度之和。

示例 1:

输入: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
输出: 11
解释:
员工1自身的重要度是5,他有两个直系下属2和3,而且2和3的重要度均为3。因此员工1的总重要度是 5 + 3 + 3 = 11。
注意:

一个员工最多有一个直系领导,但是可以有多个直系下属
员工数量不超过2000。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/employee-importance

/*
// Definition for Employee.
class Employee {
    public int id;
    public int importance;
    public List<Integer> subordinates;
};
*/

class Solution {
    public int getImportance(List<Employee> employees, int id) {
        HashMap<Integer,Employee> map = new HashMap<Integer,Employee>();
        for(Employee e:employees){
            map.put(e.id,e);
        }
        int sum_import=0;
        LinkedList<Employee> lis = new LinkedList<Employee>();
        lis.offer(map.get(id));
        Employee emp = null;
        while(true){
            emp=lis.poll();
            sum_import+=emp.importance;
            if(emp.subordinates!=null){
                Iterator<Integer> it=emp.subordinates.iterator();
                while(it.hasNext()){
                    lis.offer(map.get(it.next()));
                }
            }
            if(lis.isEmpty()){
                break;
            }
        }
        return sum_import;
    }
}

771.宝石与石头

给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。

J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。

示例 1:

输入: J = "aA", S = "aAAbbbb"
输出: 3
示例 2:

输入: J = "z", S = "ZZ"
输出: 0
注意:

S 和 J 最多含有50个字母。
 J 中的字符不重复。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jewels-and-stones

class Solution {
    public int numJewelsInStones(String J, String S) {
        int sum=0;
        HashSet<Character> set = new HashSet<Character>();
        for(int i=0;i<J.length();i++){
            set.add(J.charAt(i));
        }
        for(int i=0;i<S.length();i++){
            if(set.contains(S.charAt(i))){
                sum++;
            }
        }
        return sum;
    }
}

448.找到所有数组中消失的数字

给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[5,6]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        HashSet<Integer> set = new HashSet();
        List<Integer> lis=new ArrayList();
        for(int i=0; i<nums.length;i++){
            if(nums[i]>=1&&nums[i]<=nums.length){
                set.add(nums[i]);
            }
        }
        for(int i=1;i<=nums.length;i++){
            if(!set.contains(i)){
                lis.add(i);
            }
        }
        return lis;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值