Python刷题:简单数组(四)

16.Contains Duplicate

    Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

    给定一个整数数组和一个整数k,找出数组中两个不等的索引数i和j,使得nums[i]=nums[j],并且i与j之间差值的绝对值不大于k。

示例:

给定k=2.nums=[1,1,2,3,4],输出True。

程序:

def dup_n(nums,k):
	for i in range(len(nums)-k):
		for j in range(i+1, i+k+1):
			if nums[i] == nums[j]:
				return True
	else:
		return False

17.Missing Number

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

    给定一个数组,它包含来自于自然数序列的n个互异数字,找出该数组中丢失的某个数字。

示例:

给定nums=[0,1,3],返回2。

程序:

def miss_num(nums):
	n = len(nums) + 1
	return  int((n*(nums[0] + nums[n-2])/2) -  sum(nums)) 

18.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.

    给定一个数组nums,使用一个函数将该数组中的所有0移动到末尾,同时保证其它非零数的相对顺序。

示例:输入nums=[0,1,0,3,12],输出nums=[1,3,12,0,0]

程序:

def move_zeros(nums):
	n = len(nums)
	j = 0
	for i in nums:
		if(i != 0):
			nums[j] = i
			j+=1
	for m in range(j, n):
		nums[m] = 0

19.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).

    给定一个非空的整数数组,返回该数组中第三大的数字。如果不存在第三大的数字,返回最大的数字。时间复杂度应当为O(n)。

示例:

(1)给定[3,2,1],返回1

(2)给定[1,2],返回2

(3)给定[2,2,3,1],返回1

程序:

def third(nums):
	m1 = m2 = m3 = -1
	for num in nums:
		if num > m1:
			m2,m3 = m1,m2
			m1 = num
		elif num > m2 and num < m1:
			m3 = m2
			m2 = num
		elif num > m3 and num < m2:
			m3 = num
	return m1 if m3 == -1 else m3

20.Find All Numbers Disappeared in an array

    Given an array of integers where 1<=a[j]<=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.

    给定一个整数数组,且1<=a[j]<=n(n为数组的大小),一些元素出现两次,一些出现一次。找出[1, n]中所有的元素中没有出现在该数组中的那几个。不能使用额外的空间,且复杂度为O(n)。返回的列表不被计算为额外的空间。

示例:

输入[4,3,2,7,8,2,3,1],输出[5,6]

程序:

def find_n(nums):
	for i in range(len(nums)):
		index = abs(nums[i])-1
		nums[index] = -abs(nums[index])
	return[j+1 for j in range(len(nums)) if nums[j]>0]

猜你喜欢

转载自blog.csdn.net/zhtysw/article/details/81109400
今日推荐