Python刷题:简单数组(三)

11.Best Time to Buy and sellStockⅡ

    Say you have an array for which the ithelement is the price of a given stock on day i.

    Design an algorithm to find the maximum profit.You may complete as many transactions as you like(ie. buy one and sell oneshare of the stock multiple times). However, you may not engage in multipletransactions at the same time( ie. you must sell the stock before you buy again).

    你有一个数组,数组中的第i个元素的值代表了给定股票在第i天时的价格。

    设计一个算法找出最大的收益。你可以任意进行多次交易,但是需保证在每次购买时不持有任何股票。

题目解析:由于题目不限制买卖次数,只要求每次购买时不持有股票,因此只要在局部最低点,最高点卖出,将这个操作持续于整个周期内就可以了。

程序:

def stock(prices):
	return(sum(max(prices[i+1] - prices[i], 0) for i in range(len(prices)-1)))

12.Two SumⅡ- Input array issorted

    Given an array of integers that is alreadysorted in ascending order, find two numbers such that they add up to a specifictarget number. The function twoSum should return indices of the two numberssuch that they add up to the target, where index1 must be less than index2. Youmay assume that each input would have exactly one solution and you may not usethe same element twice.

    给定一个整数数组,该数组元素升序排列,在该数组中找出两个数字,这两个数字相加可得到给定的目标数字。该函数返回上述两个数字的索引值,并且索引值index1必须小于索引值index2.假定每一个输入都存在解,且解唯一,同一个数字不能被使用两次。

示例:

输入:numbers = [2,7, 11, 15], target = 9

输出:index1 = 1,index2 = 2

题目解析:简单来讲,可以采取先试探选取一个数字,再寻找另一个数字是否存在于该数组的方法来解决该问题,可以将暴力求解的双循环化简。

程序:

def twoSum(numbers, target):
	inter = {}                                     #创建空字典,用于存储数组中元素值和索引的关系
	for i in range(len(numbers)):
		sub = target - numbers[i]              #逻辑上只用当前值和比当前值更小的值拼凑出目标值
		if sub in inter.keys():
			return[inter[sub]+1, i+1]
		else:
			inter[numbers[i]] = i
	return []

13.Majority Element

    Given an array of size n, find the majorityelement. The majority element is the element that appears more than ⌊n/2⌋ times. You may assumethat the array is non-empty and the majority element always exist in the array.

    给定一个大小为n的数组,找出占优元素。该占优元素是该数组中出现次数超过数组元素总数一半的元素。假设该数组非空且存在占有元素,求解它。

示例:

输入:[1,1,2,2,1]

输出:1

题目解析:题目核心上就是要统计数组中每个元素出现的次数,一旦这个次数大于数组总长的一半,就认为其为占优元素。

程序:

def maj_ele(nums):
	num = nums[0]                                  #将数组的第一个元素导入进去,便于变量定义
	count = 1                                      #元素计数值,不同于以往的累加,该计数值遇到同值元素加一,非同值元素减一
	for i in nums[1:0]:                            #遍历整个数组,该方法只能针对占有元素数目大于数组长度的一半
		if count == 0:
			num, count = i,1
		else:
			if i == num:
				count = count + 1
			else:
				count = count -1
	return num

14.RotateArray

    Rotatean array of n elements to the right by k steps.

    将长度为n的数组在第k个索引值处向右旋转。(根据给定示例猜测)

示例:

给定:n=7, k=3, nums = [1,2,3,4,5,6,7]

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

题目解析:这种翻转实质上是数组拼接的一种体现,对于Python来讲,十分简单。

程序:

def rotate(n,k,nums):
	nums[:] = nums[n-k :] + nums[: n-k]

15.Contains Duplicate

    Givenan array of integers, find if the array contains any duplicates. You functionshould return true if any value appears at least twice in the array, and itshould return false if every elements is distinct.

    给定一个整数数组,如果数组包含任何重复元素,找出这个数组。如果该数组中有值出现至少两次,你的函数将返回True,如果任何元素都是独一无二的,返回False。

示例:

输入:[1,1,3,4] 返回:True

题目解析:简述主要实现的功能是确认是否有多个元素具备相同值,因此可以在遍历中判定这个值是否出现过,如果没有将其嵌入判断集合,进行下一次遍历,否则就有结果报出。但是,Python中的set()集合可以简化这种操作,因为集合元素不可重复,因此可以采用长度判断法。

程序:

def dup_n(nums):
	if len(nums) == len(set(nums)):
		return False
	else:
		return True





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值