728x90

-개발환경-

IDE : Eclipse IDE for Java Developers Version: 2020-03 (4.15.0)

공부 자료 :  www.inflearn.com/course/%EC%BD%94%EB%94%A9%ED%85%8C%EC%8A%A4%ED%8A%B8-%EC%9E%90%EB%B0%94/lecture/22652

-문제-

정수모임배열이 주어질 때, 두 숫자의 합이 target이 되는 두숫자의 모임들을 리턴하시오.

 

ex)

Given nums = [2, 8, 11, 14], target = 16, Because nums[0] + nums[3] = 2 + 14 = 16

return [1, 4].

 

-접근법-

예로 , Array = {2,8,11,14}; 가 있을 때,


1) Array Index 0 부터 끝까지 for 돌리면서,  
target -(Array 각각의 값) 을 Key로 설정 그리고 value는 Array의 인덱스로 설정.


2) Map(Array 각각의 값)=value가 이미 존재하면 그것은 two sum에 적합하므로
Array에 해당하는 인덱스와 value가 쌍으로 정답이됨

-TwoSum.java-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package codingTest;
 
import java.util.HashMap;
import java.util.Map;
 
public class TwoSum {
 
    public static void main(String[] args) {
        TwoSum a = new TwoSum();
 
        //TestCase1
        int[] nums= {2,8,11,14};
        int target = 16;
        
        int[] result = a.solve(nums,target);
        //Output
        for(int i: result) {
            System.out.print(i + " ");
        }
    }
    public int[] solve(int[] nums, int target) {
        //1. DataStructure
        int[] result= new int[2];
        Map<Integer,Integer> map =new HashMap<>();
        
        //2. for
        for(int i=0;i<nums.length;i++) {
            
            if(map.containsKey(nums[i])) { 
                int value = map.get(nums[i]);
                result[0]=value+1;
                result[1]=i+1;
            }else {
                map.put(target-nums[i], i);
            }
                
        }
    
        return result;
    }
}
 
cs
더보기

-Description

24 : Map객체를 생성한다.
29 : map 에 해당 인자값이 있는지 (bool) 여부 판단 
30~32 : if문이 만족하였으므로 , 목표로하는 두 값을 찾음.  각각의 값에 +1 씩해서 인덱스를 숫자로 표현.
34 : map에 key 값으로 target-nums[i] , value로 i를 삽입

27~37 : for 문의 계샨과정

-추가개념-

Map,HashMap
Map은 인터페이스이고 , 이를 구현한 것들중 하나가 HashMap클래스이다. 
(etc  HashMap이외에도  LinkedHashMap, TreeMap 이 존재)

 

-가져오기
import java.util.HashMap;
import java.util.Map;

 

-선언
Map<Integer,Integer> map =new HashMap<>();

 

-사용함수
map.put(key,value); // map에 데이터 삽입
             // 넣을 key가 map에 이미 존재한다면 value로 교체됨
map.get(key); // value값 추출
     // key가 존재하지 않을시 null을 가져옴
map.containsKey(key); //key 값이 map에 존재하는지 확인 (boolean 반환)
map.remove(key); // map에서 key 값을 삭제한후 value를 반환
          // 해당 key가 존재 하지 않으면 null 반환
map.size(); // map의 묶음수 출력
map.clear(); // map의 모든 내용제거
map.keySet(); // map의 모든 key를 Set<Integer>형식으로 반환(순서는 랜덤)
map.values(); // map의 모든 values를 Collection<Integer> 형식으로 반환(순서는 랜덤)
map.entrySet(); // map의 모든 key,value를 Map.Entry<Integer, Integer>형식으로 반환(순서는 랜덤)
// entrySet() 사용ex)
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() +"-" + entry.getValue());
        }

 

-추가
HashMap이외의  LinkedHashMap,TreeMap 은 순서라는 특징을 가진다.
LinkedHashMap은 입력된 순서대로 데이터가 출력되는 특징
TreeMap은 입력된 key의 정렬순으로 데이터가 출력되는 특징

 

-마침글-

인용

wikidocs.net/208#containskey

'21년이전 > 자바-Algorithm' 카테고리의 다른 글

DailyTemperature  (0) 2021.03.24
MoveZeros  (0) 2021.03.21
MeetingRoom  (0) 2021.03.20

+ Recent posts