Home [Algorithm] Hash
Post
Cancel

[Algorithm] Hash

Hash

HashMap(Key, Value)


Task

์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก in Programmers (Level 2)


๐Ÿ“Œ Problem

https://programmers.co.kr/learn/courses/30/lessons/42577

๐Ÿ“Œ Answer

1. Use HashMap

The point

  • HashMap.containsKey(String)
  • String.substring(start, end);
  • Check the splited number is in map
  • HashMap is super quick lol so, if hashmap, multi for loop was also okayโ€ฆ

Screen Shot 2021-10-24 at 1 47 21 PM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.HashMap;

class Solution {
    public boolean solution(String[] phone_book) {
        
        // put datas of phone_book to HashMap
        // Q : why number is key?
        // A : because we're gonna use 'HashMap.containsKey(String)''
        HashMap<String, Integer> map = new HashMap<>();
        for (int i = 0; i < phone_book.length; i++)
            map.put(phone_book[i], i);
        
        // check there are num in the map
        for (String num : phone_book) {
            for (int i = 1; i < num.length(); i++) {
                if (map.containsKey(num.substring(0, i)))
                    return false;
            }
        }
        
        return true;
    }
}

The source : https://coding-grandpa.tistory.com/entry/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-์ „ํ™”๋ฒˆํ˜ธ-๋ชฉ๋ก-ํ•ด์‹œ-Lv-2-์ž๋ฐ”-Java

2. Use Arrays.sort()

The point

  • Arrays.sort(String[])
    1
    2
    3
    4
    
      ex. before sorting 
          { "99", "7894", "123", "123456", "789" }
          after sorting
          { "123", "123456", "789", "7894", "99"}
    
  • String.startsWith(String)
  • But it was slower than HashMap

Screen Shot 2021-10-24 at 1 56 56 PM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.Arrays;

class Solution {
    public boolean solution(String[] phone_book) {

        Arrays.sort(phone_book);

        // you only need to compare the current number and the next number
        // because Arrays.sort();
        for (int i = 0; i < phone_book.length - 1; i++) 
            if (phone_book[i + 1].startsWith(phone_book[i])) return false;
        
        return true;
    }
}

The source : https://sso-feeling.tistory.com/318?category=922139


๐Ÿ“Œ Words

  • 2 or more, more than 2: ไปฅไธŠ
  • 2 or less : ไปฅไธ‹
  • over 2, above 2, grater than 2 : ่ถ…้Ž๏ผˆใกใ‚‡ใ†ใ‹๏ผ‰
  • under 2, below 2, less than 2 : ๆœชๆบ€๏ผˆใฟใพใ‚“๏ผ‰
This post is licensed under CC BY 4.0 by the author.

[Algorithm] Sort2

[Algorithm] Hash2

Comments powered by Disqus.