6 Nisan 2020 Pazartesi

Dizide Ardışığı Bulunan Sayıları Sayma



https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3289/


>> Solution 1 :

O(n) time, O(n) space complexity

--
import java.util.*;
import java.util.stream.*;
class CountingConsecutiveElements {
public int countElements(int[] arr) {
Map<Integer, Integer> numberCounts = new HashMap<>();
for(int num : arr) {
Integer wrappedNum = Integer.valueOf(num);
int currentCount = numberCounts.getOrDefault(wrappedNum,0);
numberCounts.put(wrappedNum,currentCount+1);
}
int result = 0;
for(Map.Entry<Integer, Integer> currentEntry: numberCounts.entrySet()) {
int currentNum = currentEntry.getKey().intValue();
int currentCount = currentEntry.getValue().intValue();
int relatedNumCount = numberCounts.getOrDefault(currentNum+1, 0);
// Even if there is only one x+1, count all x's. E.g. [1,2,2]
result += relatedNumCount == 0 ? 0 : currentCount;
}
return result;
}
}
--







Hiç yorum yok: