
nums와 정수 k가 주어졌을 때, 배열에서 nums[i] == nums[j]이고 abs(i - j) <= k인 두 개의 서로 다른 인덱스 i와 j가 있는 경우 true를 반환합니다.
HashMap을 사용하여 배열 nums의 정수와 index를 Key : Value 값으로 초기화하여 중복 되는 key가 왔을 경우 비교&연산을 하여 결과를 만들어 냈습니다.
HashMap을 사용하여 배열 nums의 date를 Key값으로, index를 value값으로 저장하고 nums의 중복된 데이터를 찾으면 index를 비교&연산합니다. k보다 같거나 작은면 true를 반환하고, 다르면 Value값을 현재 index값으로 수정합니다.class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
if(i - map.get(nums[i]) <= k)
return true;
else
map.put(nums[i], i);
}
else
map.put(nums[i], i);
}
return false;
}
}
중복된 else문 코드를 줄여 개선해 보았습니다.
map.put(nums[i], i); 작업을 하였습니다. 하지만 조금만 수정 해주면 간결한 코드로 만들 수 있어 수정하였습니다. 항상 중복된 작업이 있으면 리펙토링을 할 수 있는지 생각을 하도록 해야겠습니다.class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i]))
if (i - map.get(nums[i]) <= k) return true;
map.put(nums[i], i);
}
return false;
}
}