Java HashMap examples - Top K Frequent Elements, Two Sum

Byul·2023년 6월 13일

Java

목록 보기
7/10

source: https://leetcode.com/problems/top-k-frequent-elements/

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class App {
    public static void main(String[] args) throws Exception {
        System.out.println(Arrays.toString(new Solution().topKFrequent(new int[] { 3, 2, 2, 1, 1, 1 }, 2)));
    }
}

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        Arrays.stream(nums).forEach(num -> map.put(num, map.getOrDefault(num, 0) + 1));
        return map.entrySet().stream().sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed()).limit(k).mapToInt(Map.Entry::getKey).toArray();
    }
}

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

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class App {
    public static void main(String[] args) throws Exception {
        System.out.println(Arrays.toString(new Solution().twoSum(new int[] { 2, 7, 11, 15 }, 9)));
    }
}

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) return new int[] {i, map.get(target - nums[i])};
            map.put(nums[i], i);
        }
        return null;
    }
}
profile
junior backend developer

0개의 댓글