283. Move Zeroes
Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
给定一个数组,写一个函数,将数组中的0都移动到数组末尾,同时保持非零数字的顺序。
比如,数组nums=[0, 1, 0, 3, 12],调用你的函数后,数组变成[1, 3, 12, 0, 0]。
注意:
1. 你必须在原数组上进行修改,不能拷贝一个新数组;
2. 尽量减少你的操作次数。
思路:
从后向前搜索,把找到的0都移动到最后,即,将找到的0后面的非零数向前移动。
class Solution:
def moveZeroes(self, nums):
for i in range(len(nums)-1,-1,-1):
if nums[i]==0:
for j in range(i+1,len(nums)):
if nums[j]!=0:
nums[j-1]=nums[j]
nums[j]=0
414. Third Maximum Number
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1.
Example 2:
Input: [1, 2] Output: 2 Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1] Output: 1 Explanation: Note that the third maximum here means the third maximum distinct number. Both numbers with value 2 are both considered as second maximum.
返回数组中的最大的第三个数,需要注意的是,如果数组的长度小于3,直接返回最大的数就好,如果数组的长度刚好等于3,直接返回最小的数就好。注意,重复的数字当成一个数字看。所以需要先set()
一下。
class Solution:
def thirdMax(self, nums):
nums=set(nums)
n=len(nums)
if n<3:
return max(nums)
elif n==3:
return min(nums)
else:
nums.remove(max(nums))
nums.remove(max(nums))
return max(nums)
442. Find All Duplicates in an Array
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?
Example:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
给定一个整数数组,1≤a[i]≤n (n =数组大小),有些元素出现两次,有些元素出现一次。
查找此数组中出现两次的所有元素。
你能在没有额外空间的情况下在O(n)运行时完成吗?
思路:先对数组进行sort排序,然后遍历排序后的数组,如果前后坐标中的值相同,则说明该值重复,放入结果数组中,最后返回结果数组。
class Solution:
def findDuplicates(self, nums):
nums.sort()
result=[]
for i in range(0,len(nums)-1):
if nums[i]==nums[i+1]:
result.append(nums[i])
i+=1
return result
448. Find All Numbers Disappeared in an Array
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]
给定一个整数数组,其中1≤a[i]≤n (n =数组大小),有些元素出现两次,有些元素出现一次。
找到[1,n]中不出现在该数组中的所有元素。
你能在没有额外空间的情况下在O(n)运行时完成吗?您可以假设返回的列表不算作额外的空间。
思路:巧妙利用set
class Solution:
def findDisappearedNumbers(self, nums):
return list(set(range(1,len(nums)+1))-set(nums))