leetcode练习(441,442)python实现

题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 结果:
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值