ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 딕셔너리
    알고리즘 2023. 12. 3. 19:17

    nums의 두 원소를 더해 target을 만들 수 있으면 True, 없으면 False return.

    input: nums = {4,1,9,7,5,3,16}, target: 14, output: True

    input: nums = {2,1,5,7}, target: 4, output: False

    input: nums = {2,2,3}, target: 4, output: True

    조건: 같은 원소는 중복으로 더할 수 없다.

    import java.util.HashMap;
    
    public class DictionaryTesg {
    	
    	public static boolean dic(int[] nums, int target) {
    		HashMap<Integer, Integer> map = new HashMap<>();
    		for(int i: nums) {
    			map.put(i, map.getOrDefault(i, 0) + 1);
    		}
    		for(int j=0; j<nums.length; j++) {
    			if(map.get(nums[j]) == 1 && nums[j] != target-nums[j] && map.containsKey(target-nums[j])) {
    				return true;
    			}else if(map.get(nums[j]) > 1 && map.containsKey(target-nums[j])) {
    				return true;
    			}
    		}
    		return false;
    	}
    
    	public static void main(String[] args) {
    		int[] nums = {4,1,9,7,5,3,16};
    		int[] nums2 = {2,1,5,7};
    		
    		System.out.println(dic(nums, 14));
    	}
    
    }

    '알고리즘' 카테고리의 다른 글

    재귀  (1) 2023.12.03
    Dictionary - 가장 긴 연속된 수열  (4) 2023.12.03
    LIFO - java  (0) 2023.12.02
    스택(stack)  (0) 2023.12.02
    Two Pointer  (2) 2023.12.02
Designed by Tistory.