연습문제_해시맵

2023. 2. 18. 00:27자료구조/선형자료구조

< 언제 사용? > - 검색을 많이 필요할 때. 상황에 맞는 해시 함수가 존재할 때.


1번. 해시 테이블을 이용한 수 찾기

/*
    주어진 첫 번째 배열을 이용해 해시 테이블을 초기화 한 후,
    두번째 배열이 주어졌을 때 해당 배열 내 데이터가 해시 테이블에 있는지 확인

    예시)
    배열1: 1,3,5,7,9
    배열2: 1,2,3,4,5
    출력: true, false, true, false, true
*/
import java.util.Hashtable;

public class quiz1 {
    public static void solution(int[] arr1, int[] arr2) {
        Hashtable<Integer, Integer> ht = new Hashtable();
        for (int i = 0; i < arr1.length; i++) {
            ht.put(i, arr1[i]);
        }

        for (int i = 0; i < arr2.length; i++) {
            if (ht.containsValue(arr2[i])) {
                System.out.println("true");
            } else {
                System.out.println("false");
            }
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] arr1 = {1,3,5,7,9};
        int[] arr2 = {1,2,3,4,5};
        solution(arr1, arr2);
    }
}

 


★ 2번. 정수형 배열 nums와 target이 주어졌을 때, nums에서 임의의 두 수를 더해 target을 구할 수 있는지 확인

/*
    두 수의 합으로 target을 구할 수 있으면 해당값의 index를 반환하고, 없는 경우 null 반환

    예시)
    nums: 7,11,5,3
    target: 10
    출력: 0, 3

    nums: 8,3,-2
    target: 6
    출력: 0,2
*/
import java.util.Arrays;
import java.util.Hashtable;

public class quiz2 {
    public static int[] solution(int[] numbers, int target) {
        int[] result = new int[2];
        Hashtable<Integer, Integer> ht = new Hashtable<>();

        for (int i = 0; i < numbers.length; i++) {
            if (ht.containsKey(numbers[i])) {
                result[0] = ht.get(numbers[i]);
                result[1] = i;
                return result;
            }
            ht.put(target - numbers[i], i);
        }
        return null;
    }

    public static void main(String[] args) {
        int[] nums = {7,11,5,3};
        System.out.println(Arrays.toString(solution(nums, 10)));

        nums = new int[]{8,3,-2};
        System.out.println(Arrays.toString(solution(nums, 6)));

        nums = new int[]{1,2,3};
        System.out.println(Arrays.toString(solution(nums, 12)));
    }
}

- 출력

 

'자료구조 > 선형자료구조' 카테고리의 다른 글

연결리스트  (0) 2023.02.18
해시테이블  (0) 2023.02.18
연습문제_배열  (0) 2023.02.15
배열  (0) 2023.02.15
연습문제_큐  (0) 2023.02.15