티스토리 뷰

728x90
반응형

 MAP 

1. 생성자 : Map <String, Integer> hm = new HashMap();

- HashMap 기본 메서드

Map<KeyType, ValueType> maps = new HashMap<KeyType, ValueType>();

- HashMap 객체를 생성

- 다음과 같음

HashMap<String , Integer> hmap = new HashMap<String , Integer>();

Map<String, Integer> map = new HashMap<String, integer>();

 

2. 메소드 : HashMap Method

- void clear() : HashMap에 저장된 모든 객체를 제거한다.

ex) map.clear()

- Object clone() : 현재 HashMap을 복제하여 반환한다.

ex) mymap = (HashMap)map.clone();

- boolean containsKey(Object Key) : HashMap에 지정된 키(Key)가 포함되어 있는지 알려준다.

- boolean containsValue(Object Value) : HashMap에 지정된 값(Value)이 포함되어 있는지 알려준다.

- Set entrySet() : HashMap에 저장된 key-value 값을 엔트리의 형태로 set에 저장하여 반환한다.

ex)map.put("A", 1);

      map.put("B", 2);

      map.put("C", 3);

      Set set = map.entrySet();

      System.out.println("set values are" + set);

      (result) set values : [A=1,B=2,C=3]

- Object get(Obejct Key) : 지정된 Key의 값을 반환한다.

ex)map.put("A", 1);

      map.put("B", 2);

      map.put("C", 3);

      String val = (String)map.get("B");

      System.out.println("Value for key B is: " + val);

      (result) Value for key B is 2

- boolean isEmpty : HashMap이 비어있는지 확인한다.

ex) boolean val = map.isEmpty();

- Set keySet() : HashMap에 저장된 모든 키가 저장된 Set을 반환한다.

ex)map.put("A", 1);

      map.put("B", 2);

      map.put("C", 3);

      Set keyset = map.keySet();

      System.out.println("Key set values are" + keyset);

      (result) Key set values are [A,B,C]

- Object put(Object Key, Object Value) : HashMap에 키와 값을 저장한다.

ex)map.put("A", "aaa");

      map.put("B", "bbb");

      map.put("C", "ccc");

- void putAll(Map m) : Map에 해당하는 모든 요소를 HashMap에 저장한다.

- Object remove(Object Key) : HashMap에서 지정된 키로 지정된 값을 제거한다.

ex) map.remove("key");

- int size() : HashMap에 저장된 요소의 개수를 반환한다.

- Collection values() : HashMap에 저장된 모든 값을 컬렉션 형태로 반환한다.

 

3. 특징

- Map 은 Key 와 Value 로 구성된 객체를 저장한다.

- 키는 중복 저장될 수 없다.

- Map으로 구현하는 클래스는 아래와 같다. 

HashMap

TreeMap

LinkedHashMap

Hashtable

 

4. 참조

HashMap에 대한 자세한 내용은 아래 링크를 참고하자. 

http://d2.naver.com/helloworld/831311

 

5. LinkedHashMap 

입력된 순서를 기억하는 HashMap이다. 아래와 같이 하면 입력한 순서대로 출력하는 것을 확인할 수 있다. 물론 그냥 HashMap은 순서대로 출력되지 않는다. 

Map<String, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("이름", "Eddy.Kim");
linkedHashMap.put("나이", "비밀");
linkedHashMap.put("업종", "포털");
linkedHashMap.put("사는곳", "서울");
linkedHashMap.forEach((key, value) -> System.out.println(key + value));

아래 링크에서 좋은 내용을 참고할수 있다.

http://www.baeldung.com/java-linked-hashmap

 

6. Set

Set 은 중복된 요소를 포함할 수 없다. List 와는 다르게 인덱스를 사용하지 않기 때문에, 인덱스 매개변수가 없다.

Set 인터페이스를 구현한 클래스는 아래와 같다 

HashSet

Linked HashSet

TreeSet

 

7. Sorting

타입에 따라서 다르다. 

HashSet : 랜덤

LinkedHashSet : 입력 순서대로

TreeSet : comparator에 의해서

 

//a. HashSet 랜덤 정렬
Set<String> set1 = new HashSet<>();
set1.add("이진우");
set1.add("김정우");
set1.add("김시은");
System.out.println("HashSet_랜덤정렬_"+set1);

Result : HashSet_랜덤정렬_[김시은, 이진우, 김정우]


//b. LinkedHashSet 입력 순서대로 정렬
Set<String> set2 = new LinkedHashSet<>();
set2.add("이진우");
set2.add("김정우");
set2.add("김시은");
System.out.println("LinkedHashSet_입력순서대로_"+set2);

LinkedHashSet_입력순서대로_[이진우, 김정우, 김시은]

 

//c. TreeSet Comparator에 의해서
Set<String> set3 = new TreeSet<>(Comparator.reverseOrder());
set3.add("이진우");
set3.add("김정우");
set3.add("김시은");
System.out.println("TreeSet_Comparator_"+set3);

TreeSet_Comparator_[이진우, 김정우, 김시은]

 

//d. Stream API 를 사용하여, List 로 변환

Set<String> set = new HashSet<>();
set.add("김시은");
set.add("이진우");
set.add("김정우");
List<String> list = set.stream().collect(Collectors.toList());
System.out.println(list);

 

8. Example

a. HashMap get/put/keySet/getOrDefault

import java.util.*;
class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        Map <String, Integer> hm = new HashMap();
        for(String part : participant) hm.put(part, hm.getOrDefault(part, 0) + 1);
        for(String comp : completion) hm.put(comp, hm.get(comp) -1);
        for(String key : hm.keySet()) if(hm.get(key) != 0) answer = key;
        return answer;
    }
}

b. substring, equals, Arrays.sort, String to Integer, Integer to String, startWith, endWith, includes

import java.util.*;

class Solution {
    public boolean solution(String[] phone_book) {
        boolean answer = true;
        
        //1. hard coding
        //int[] phone_number = new int[phone_book.length];
        //for(int i =0;i<phone_book.length;i++){
        //    phone_number[i] = Integer.parseInt(phone_book[i]);
        //}
        //Arrays.sort(phone_number);
        //for(int i =0;i<phone_number.length;i++){
        //    phone_book[i] = Integer.toString(phone_number[i]);
        //}
        //for(int i =0;i<phone_book.length;i++){
        //    for(int j =i+1;j<phone_book.length;j++){
        //        if(phone_book[i].equals(phone_book[j].substring(0,phone_book[i].length()))){
        //            answer = false;
        //            break;
        //        }
        //    }
        //}
        
        //2. compare
        //for(int i =0;i<phone_book.length;i++){
        //    for(int j =0;j<phone_book.length;j++){
        //        if(i != j && phone_book[i].length() <= phone_book[j].length()){
        //            if(phone_book[i].equals(phone_book[j].substring(0,phone_book[i].length()))){
        //                answer = false;
        //                break;
        //            }
        //        }
        //    }
        //}
        
        //3. startWith
        for(int i=0; i<phone_book.length-1; i++){
            for(int j=i+1; j<phone_book.length; j++){
                if(phone_book[i].startsWith(phone_book[j])) 
                    return false;
                if(phone_book[j].startsWith(phone_book[i])) 
                    return false;
            }
        }
        return true;
    }
}

c. put, get, size, keySet, clothes.length & String.length(), getOrDefault

import java.util.*;

class Solution {
    public int solution(String[][] clothes) {
        int answer = 0;
        Map <String, Integer> hm = new HashMap();
        System.out.println(clothes.length);
        for(int i =0;i<clothes.length;i++){
            hm.put(clothes[i][1], hm.getOrDefault(clothes[i][1], 0) + 1);
        }
        if(hm.size() == 1){
            for(String key : hm.keySet()) answer = hm.get(key);
        }else{
            int val = 1;
            for(String key : hm.keySet()) {
                val *= (hm.get(key) +1);
            }
            answer = val -1;
        }
        return answer;
    }
}

 Arrays 

1. Array

a. 소규모 배열 (성능 고려하지 않음) : public static void sort(int[] a)

import java.util.*;

class Solution {
    public String solution(int[] numbers) {
        String answer = "";
        Arrays.sort(numbers);
        for(int i =0;i<numbers.length;i++){
            System.out.println(numbers[i]);
        }
        return answer;
    }
}

b. 대규모 배열 (성능 고려) : public static <T> void sort(T[] a, Comparator <? super T> c)

import java.util.Arrays;
import java.util.Comparator;
 
class Solution {
    public String solution(int[] numbers) {
        String answer = "";

        String[] arr = new String[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            arr[i] = (String.valueOf(numbers[i]));
        }

        Arrays.sort(arr, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return (s2+s1).compareTo(s1+s2);
            }
        });

        if (arr[0].equals("0")) return "0";

        for (int i = 0; i < arr.length; i++) {
            answer+=arr[i];
        }
        return answer;
    }
}

2. Sample

a. Arrays.sort, Arrays.copyOfRange

import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
    	//int[] answer = new int[commands.length];
        //for(int i=0; i<commands.length; i++){
        //    int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
        //    Arrays.sort(temp);
        //    answer[i] = temp[commands[i][2]-1];
        //}
        
        int[] answer = new int[commands.length];
        int[] result;
        for(int i = 0 ;i<commands.length; i++){
            result = new int[commands[i][1] - commands[i][0] +1];
            for(int j = 0;j<(commands[i][1] - commands[i][0] +1);j++){
                result[j] = array[commands[i][0] - 1 + j];
            }
            Arrays.sort(result);
            answer[i] = result[commands[i][2]-1];
        }
        return answer;
    }
}

b. Arrays.sort, Comparator

import java.util.*;

class Solution {
    public String solution(int[] numbers) {
        String[] nums = new String[numbers.length];

        for (int i=0; i<nums.length; i++) 
            nums[i] = numbers[i] + "";

        Arrays.sort(nums, new Comparator<String>() {
            public int compare(String o1, String o2) {
                return (o2 + o1).compareTo(o1 + o2);
            }
        });

        String ans = "";
        for (int i=0; i<numbers.length; i++)
            ans += nums[i];

        return ans.charAt(0) == '0' ? "0" : ans;
    }
}

c. Arrays.sort 내림차순 (i--, Collections.reverseOrder)

import java.util.*;

class Solution {
    public int solution(int[] citations) {
        //Arrays.sort(citations);

        //int max = 0;
        //for(int i = citations.length-1; i > -1; i--){
        //    int min = (int)Math.min(citations[i], citations.length - i);
        //    if(max < min) max = min;
        //}

        //return max;

        int answer = 0;
        Integer[] arrTemp = new Integer[citations.length];
        for(int i =0;i<citations.length;i++){
            arrTemp[i] = citations[i];
        }
        Arrays.sort(arrTemp,Collections.reverseOrder());
        for(int i =0;i<arrTemp.length;i++){
            System.out.println(arrTemp[i]);
            if(i+1 > arrTemp[i]){
                break;
            }
            answer = i+1;
        }
        return answer;
    }
}

 완전탐색 

1. Sample

a. List, ArrayList, list.add, list.get, list.size

import java.util.*;
class Solution {
    public int[] solution(int[] answers) {
        int[] answer;
        int[] gg1 = {1,2,3,4,5};
        int[] gg2 = {2,1,2,3,2,4,2,5};
        int[] gg3 = {3,3,1,1,2,2,4,4,5,5};
        
        int[] cnt = new int[3];
        for(int i=0;i<answers.length;i++){
            if(answers[i] == gg1[i%5]){
                cnt[0]++;
            }
            if(answers[i] == gg2[i%8]){
                cnt[1]++;
            }
            if(answers[i] == gg3[i%10]){
                cnt[2]++;
            }
        }
        int win = cnt[0];
        for(int i =0;i<3;i++){
            if(win < cnt[i]){
                win = cnt[i];
            }
        }
        List<Integer> user = new ArrayList();
        for(int i=0;i<3;i++){
            if(win == cnt[i]){
                user.add(i);
            }
        }
        answer = new int[user.size()];
        for(int i =0;i<user.size();i++){
            answer[i] = user.get(i)+1;
        }
        return answer;
    }
}

b. List, ArrayList

import java.util.*;
import java.lang.*;

class Solution {
    public int solution(String numbers) {
        int answer = 0;
        int index = 0;
        Permutation ex = new Permutation();
        String [] s = numbers.split("");
        ArrayList <String> t = new ArrayList<String>();
        ArrayList <Integer> t2 = new ArrayList <Integer>();
        
        for(int i=0;i<s.length ;i++){
            String [] combArr = new String[i+1];
            ex.doCombination(t,combArr,s,s.length,i+1,0,0);
        }
        System.out.println(t.toString());
        
        for(String ss : t){
            t2.add(Integer.valueOf(ss));
        }
        
        HashSet hm = new HashSet(t2);
        t2.clear();
        t2.addAll(hm);
        
        //search for prime number
        for(int num=0; num < t2.size();num++){
            int number = t2.get(num);
            if(number == 1)
                t2.set(num,0);
            for(int p=2; p <number;p++){
                    if(number%p == 0){
                        t2.set(num,0);
                        break;
                    }
            }
        }
        
        for(int i=0;i<t2.size();i++){
            if(t2.get(i) != 0){
                answer++;
            }
        }
        return answer;
    }
}
class Permutation{
   public void doCombination(ArrayList <String> t,String[] combArr, String[] arr, int n, int r, int index, int target){
        if(r == 0){
            //to-do: combArr permutation
            doPermutation(t,combArr, 0);
        }else if(target == n) return;
        else{
            combArr[index] = arr[target];
            // System.out.println(Arrays.toString(combArr));
            doCombination(t,combArr, arr, n, r-1, index+1, target+1);
            doCombination(t,combArr, arr, n, r, index, target+1);
        }
    }

    public void doPermutation(ArrayList<String> t,String[] arr, int startIdx){
        int length = arr.length;
        if(startIdx == length){
            String temp = "";
            for(int i=0;i<arr.length;i++){
                temp += arr[i];
            }
            t.add(temp);
            return;
        }
        for(int i=startIdx; i<length; i++){
            swap(arr, startIdx, i);
            doPermutation(t,arr, startIdx+1);
            swap(arr, startIdx, i);
        }
    }

    public void swap(String[] arr, int n1, int n2){
        String temp = arr[n1];
        arr[n1] = arr[n2];
        arr[n2] = temp;
    }
}

ㅇㅇ

728x90
반응형