My LeetCode Diary - Day6 HashTable

242. Valid Anagram

Link

images

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] hash = new int[26];

        for (int i=0;i<s.length();i++) {
            hash[s.charAt(i)-'a']++;
        }

        for (int i=0; i<t.length(); i++){
            hash[t.charAt(i)-'a']--;
        }

        for (int num : hash){
            if (num != 0) {
                return false;
            }
        }
        return true;
    }
}

202. Happy Number

Link

class Solution {
    public boolean isHappy(int n) {
       HashSet<Integer> seen = new HashSet<>();
       while (n!=1){
           int current = n;
           int sum = 0;
           while (current != 0) {
               sum += (current%10) * (current%10);
               current /= 10;
           }
           if (seen.contains(sum)) {
               return false;
           }
           seen.add(sum);
           n = sum;
       }
       return true;
    }

    
}

1. Two Sum

Link

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        for (int i = 0; i < nums.length; i++){
            for(int j = i+1; j < nums.length;j++){
                if (nums[i] + nums[j] == target){
                    res[0] = i;
                    res[1] = j;
                }
            }
        }
        return res;
    }
}

images

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