avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

Python beat98.40% collectionsofCounter method!

  2024-01-01        
字数统计: 214字   |   阅读时长: 1min

Pyhton collection In the bag Counter() Be rightlist里出现of元素conduct计数,And the output is a dictionary。
for examplenums=[1, 1, 1, 2, 2, 3] ToCounter后of结果是Counter({1: 3, 2: 2, 3: 1})。

  1. So traverse a dictionary,whenvalue>3of时候value=2,Can be greater than2indivualof元素计数become2indivual。
  2. So we willCounter({1: 3, 2: 2, 3: 1})becomeCounter({1: 2, 2: 2, 3: 1})后再Toelementsconductlist操作就可以得到改变后of列表了。

Due to the meaning of the question“Input the array「Quote」方式传递of”,So we willnumsJust fill in and fill in

1
2
3
4
5
6
7
8
9
10
11
from collections import Counter # Imported package
class Solution:
def removeDuplicates(self, nums: List[int]) -> List[int]:
dict1 = Counter(nums)
for i in dict1:
if dict1[i] > 2:
dict1[i] = 2
list1 = list(dict1.elements())
nums.clear() # clear the list
nums.extend(list1) # Add the collection to the list
return len(nums)

Complexity analysis

time complexity:O(n),in n 是数组of长度。We have a maximum of this array once。

Spatial complexity:O(1)。我们只需要常数of空间存储若干变量。

  • Python
  • solved,answer

扫一扫,分享到微信

微信分享二维码
704. Two -point search
977.Orderly array square
目录
ahoh, this article has no catalog.

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号