LeetCode---Rotate Array、Missing Number

47 篇文章 0 订阅
38 篇文章 0 订阅

189. Rotate Array

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Note:

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

本题的意思是给定一个数组,将数组向右旋转k步,其中k是非负的

此处可以先来复习一下python的两个方法:insert()和pop()

insert() 函数用于将指定对象插入列表的指定位置。

insert()方法语法:

list.insert(index, obj)
  • index -- 对象 obj 需要插入的索引位置。
  • obj -- 要插入列表中的对象。

该方法没有返回值,但会在列表指定位置插入对象。

pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

pop()方法语法:

list.pop([index=-1])
  • obj -- 可选参数,要移除列表元素的索引值,不能超过列表总长度,默认为 index=-1,删除最后一个列表值。

该方法返回从列表中移除的元素对象。

所以本题可以利用这两个方法来求解

class Solution:
    def rotate(self, nums, k):
        while k>0:
            nums.insert(0,nums.pop())
            k-=1

268. Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

class Solution:
    def missingNumber(self, nums):
        n=len(nums)
        asum=n*(n+1)//2
        return asum-sum(nums)

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值