题441
题目要求是按照把n按照1+2+…+m,如果m行不含m个数,就返回该行的序号。
You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
Given n, find the total number of full staircase rows that can be formed.
n is a non-negative integer and fits within the range of a 32-bit signed integer.
Example 1:
n = 5
The coins can form the following rows:
¤
¤ ¤
¤ ¤
Because the 3rd row is incomplete, we return 2.
Example 2:
n = 8
The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
Because the 4th row is incomplete, we return 3.
我的思路是:按照常理判断,一般最多有int(n/2)+1行,所以用while(i<=int(n/2)+1)判断,n = n-i,如果n<0,就break,返回i-1;否则,就i+1,继续循环。注意这里一开始,我是用for循环做的,但是在submit的时候会出现memory出错,因为输入一个过大的数,i的存储会出现问题,后来改用while,就能accept了。
代码如下:
import copy
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
if n<=0:
return 0
i = 1
m = int(n/2)+1
while i<=m:
n = n - i
if n<0:
break
i += 1
return i-1
s = Solution()
print(s.arrangeCoins(8))
结果如下:
submit结果:
题442
题目要求:在一个int数组中找出出现过2次的数。
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
关键1:1 ≤ a[i] ≤ n (n = size of array),
关键2:without extra space and in O(n) runtime
我的思路是:对于list中的每一个数i,令nums[abs(i)-1]取它对应的负数,如果遇到前面已经出现过的数,则它要置负数的那个位置的数已经为负了,此时只要判断一下,就可知道是不是已经出现过。
代码如下:
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res= []
for i in nums:
if nums[abs(i) - 1] < 0:
res.append(abs(i))
else:
nums[abs(i) - 1] = -nums[abs(i) - 1]
return res
s= Solution()
nums =[4,3,2,7,8,2,3,1]
print(s.findDuplicates(nums))
结果如下:
submit 结果: