{
"name": "darcy",
"city": "shenzhen"
}
wilkice / leetcode Goto Github PK
View Code? Open in Web Editor NEWLeetcode problems
License: MIT License
Leetcode problems
License: MIT License
{
"name": "darcy",
"city": "shenzhen"
}
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
第一种遍历:O(n2)
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
return [sum(i > j for j in nums) for i in nums]
第二种先排序后遍历:O(nlogn)
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
sorted_nums = sorted(nums)
return [sorted_nums.index(num) for num in nums]
nlogn(排序) + n = nlogn
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/
分析题目可以得知此题解法与 bit 有关。当最后一位 bit 是 1(并且此时值不为1)的时候,需要2步(1步是减去1,1步是除以2),当最后一位 bit 是0的时候,只需要一步,即除以2.
解法一:
class Solution:
def numberOfSteps (self, num: int) -> int:
total = 0
# num 为0或者1,直接返回0或1
if num <= 1:
return num
while num >1:
# 如果 num 为奇数,则加2步
if num & 1 == 1:
total += 2
# 偶数加1步
else:
total += 1
num >>= 1
# +1 是因为上面的循环在num=1的时候退出,所以此时需要加上1变为0的步数
return total+1
解法二(推荐):直接计算bit中1和0的个数
class Solution:
def numberOfSteps (self, num: int) -> int:
value = f'{num:b}' # 也可以用 bin(num)[2:]
return value.count("1") -1 + len(value)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.