diff --git a/Jacklin/contains_duplicate.py b/Jacklin/contains_duplicate.py new file mode 100644 index 0000000..eb20748 --- /dev/null +++ b/Jacklin/contains_duplicate.py @@ -0,0 +1,9 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + seen = set() + for num in nums: + if num in seen: + return True + else: + seen.add(num) + return False \ No newline at end of file diff --git a/Jacklin/groupanagram.py b/Jacklin/groupanagram.py new file mode 100644 index 0000000..b487bcc --- /dev/null +++ b/Jacklin/groupanagram.py @@ -0,0 +1,9 @@ +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + anagramGroups = defaultdict(list) + + for word in strs: + sortedWord = ''.join(sorted(word)) + anagramGroups[sortedWord].append(word) + + return list(anagramGroups.values()) \ No newline at end of file diff --git a/Jacklin/plusone.py b/Jacklin/plusone.py new file mode 100644 index 0000000..1e9e835 --- /dev/null +++ b/Jacklin/plusone.py @@ -0,0 +1,9 @@ +class Solution: + def plusOne(self, digits: List[int]) -> List[int]: + n = len(digits) + for i in range(n - 1, -1, -1): + if digits[i] < 9: + digits[i] += 1 + return digits + digits[i] = 0 + return [1] + digits \ No newline at end of file diff --git a/Jacklin/product_exceptself.py b/Jacklin/product_exceptself.py new file mode 100644 index 0000000..89df424 --- /dev/null +++ b/Jacklin/product_exceptself.py @@ -0,0 +1,14 @@ +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + answer = [1] * n + prefix = 1 + for i in range(n): + answer[i] = prefix + prefix *= nums[i] + suffix = 1 + for i in range(n - 1, -1, -1): + answer[i] *= suffix + suffix *= nums[i] + + return answer \ No newline at end of file diff --git a/Jacklin/topk.py b/Jacklin/topk.py new file mode 100644 index 0000000..e8a4a60 --- /dev/null +++ b/Jacklin/topk.py @@ -0,0 +1,15 @@ +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + + frequency = Counter(nums) + buckets = [[] for _ in range(len(nums) + 1)] + + for num, freq in frequency.items(): + buckets[freq].append(num) + + result = [] + for i in range(len(buckets) - 1, 0, -1): + if buckets[i]: + result.extend(buckets[i]) + if len(result) >= k: + return result[:k] diff --git a/Jacklin/twosum.py b/Jacklin/twosum.py new file mode 100644 index 0000000..9e4ee6f --- /dev/null +++ b/Jacklin/twosum.py @@ -0,0 +1,8 @@ +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + h = {} + for i, n in enumerate(nums): + c = target - n + if c in h: + return [h[c], i] + h[n] = i diff --git a/Jacklin/validanagram.py b/Jacklin/validanagram.py new file mode 100644 index 0000000..3c5c6dd --- /dev/null +++ b/Jacklin/validanagram.py @@ -0,0 +1,5 @@ +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + return Counter(s) == Counter(t) \ No newline at end of file