代码随想录算法训练营第5天 | (Hash) Leetcode 242, 349, 202, 1

本文介绍了如何使用Java的HashMap和HashSet数据结构解决LeetCode中的四个问题:检查两个字符串是否为变位词(Anagram)、找出两个整数数组的交集、判断一个数是否为快乐数(HappyNumber),以及查找数组中和为目标值的两个数的索引。
摘要由CSDN通过智能技术生成

242. Valid Anagram

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

HashMap

it is a class to implement map <key, value> pair

           K          V

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

map.put(K key, V value)    -> return V
if key exists, update its value to new value, return old value
if key not exist, add this pair, return null

map.get(Object key)  if exist, return value; not exist return null

有可能k和V存的都是null,所以不能用此方法看是否存在

map.remove(Object key) -> return old value  not exist return null

boolean map.containsKey(Object key)  exist return true
给一个key看是否存在

map.getOrDefault(Object key, V defaultValue) This method returns value mapped with the specified key, otherwise default value is returned.

boolean containsValue(Object value) - O(n)
void clear()
int size()
boolean isEmpty()

map.replace(key, value) if the key does not exist, won’t change anything. if the key exists, change to value.

converts the given string into a sequence of characters.
char[] arrayS = s.toCharArray();

class Solution {
    public boolean isAnagram(String s, String t) {
    // converts the given string into a sequence of characters.
        // char[] arrayS = s.toCharArray();
        Map<Character,Integer> map = new HashMap<>();
        for (char s1 : s.toCharArray()) {
            if (map.containsKey(s1)) {
                map.put(s1, map.get(s1) + 1);
            } else {
                map.put(s1, 1);
            }
        }
        // char[] arrayT = t.toCharArray();
        for (char t1 : t.toCharArray()) {
            if (map.containsKey(t1)) {
                map.put(t1, map.get(t1) - 1);
            } else {
                return false;
            }
        }
        // check if any char has non-zero value.
        for (int val : map.values()) {
            if (val != 0) {
                return false;
            }
        }
        return true;

    }
}
349. Intersection of Two Arrays

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order

HashSet

A HashSet is a collection of items where every item is unique.
HashSet<Integer> cars = new HashSet<>();
cars.add(1);
cars.contains(1);
cars.remove(1);
cars.size()

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set =  new HashSet<>();
        for (int i : nums1) {
            set.add(i);
        }
        ArrayList<Integer> list = new ArrayList<>();
        for (int j: nums2) {
            if (set.contains(j)) {
                list.add(j);
// don't forget to remove the element from set
// otherwise we will add duplicate element to the list.
                set.remove(j);
            }
        }
        int[] arr = new int[list.size()];
        int index = 0;
        for (Integer x : list) {
            arr[index] = x;
            index++;
        }
        return arr;
    }
}
202. Happy Number

Write an algorithm to determine if a number n is happy.

happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

Example 1:

Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

I got to know the pattern after watching Neetcode's video.

if we get 1 again, then it is true.

if we get a number other than 1 again, then it is false.

 how can we get each digit?

class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> set = new HashSet<>();
        while (n != 1) {
            set.add(n);
            n = getSumOfDigits(n);
            if (set.contains(n) && n != 1) {
                return false;
            }
        }
        return true;
    }

    public int getSumOfDigits(int n) {
        int sum = 0;
        while (n > 0) {
            int temp = n % 10; //get the last digit
            sum += temp * temp; // sum digits
            n = n / 10; // get the second last digit
        } //stay in the while loop until we sum all the digits
        return sum;
    }
}
1. Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

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

TC: O(n)

SC: O(n)

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值