반응형

HashMap 3

[Leetcode/Hashmap] 242. Anagram (feat.Java)

https://leetcode.com/problems/valid-anagram/ class Solution { public boolean isAnagram(String s, String t) { HashMap hm = new HashMap(); boolean answer = true; // s의 캐릭터를 hm에 담는다. // key에 없으면 1로 디폴트 세팅, 있으면 값에 +1 for(int i = 0; i < s.length(); i++){ if(hm.containsKey(s.charAt(i))){ System.out.print(hm.get(s.charAt(i))); hm.put(s.charAt(i), hm.get(s.charAt(i))+1); } else { hm.put(s.charAt(i), 1);..

[Leetcode/Hashmap] 217. Contains Duplicate (feat.Java)

https://leetcode.com/problems/contains-duplicate/description/ class Solution { public boolean containsDuplicate(int[] nums) { HashMap hm = new HashMap(); boolean answer = false; for(int i = 0; i < nums.length; i++){ if(hm.containsKey(nums[i])){ answer = true; break; } else { hm.put(nums[i], true); } } return answer; } } 해시맵을 알고리즘에 접목하면 이전의 데이터들을 저장해놨다가 바로 꺼내다 로직을 만들 수 있다는 장점이 있다. 루프를 돌며 이미 저장된 값..

반응형