本文主要是介绍LeetCode初级算法练习——数组篇,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
数组篇
26. 从排序数组中删除重复项
给定一个有序数组,你需要原地删除其中的重复内容,使每个元素只出现一次,并返回新的长度。
不要另外定义一个数组,您必须通过用 O(1) 额外内存原地修改输入的数组来做到这一点。
示例:
给定数组: nums = [1,1,2],你的函数应该返回新长度 2, 并且原数组nums的前两个元素必须是1和2 不需要理会新的数组长度后面的元素
Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example:
Given nums = [1,1,2],Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
class Solution:def removeDuplicates(self, nums):""":type nums: List[int]:rtype: int前提是已排序判断nums[j]与nums[i-1]元素,相等j+1继续判断下一元素;不相等,nums[j]赋值给nums[i],返回i与size的最小值(size为0时返回size,没有不相同的时候 size==i,有相同的i<size)"""i = 1 j = 1size = len(nums)while j < size:if nums[j] == nums[i-1]:j += 1else: nums[i] = nums[j]i += 1j += 1return min(i,size)
122.买卖股票的最佳时机 II—— best time to buy and shell stock II
假设有一个数组,它的第 i 个元素是一个给定的股票在第 i 天的价格。设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。
Say you have an array for which the ith element 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 one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
class Solution:def maxProfit(self, prices):""":type prices: List[int]:rtype: int"""total = 0#当len(prices)==0时,不进行for循环,直接ruturn totalfor i in range(1,len(prices)):total += max(0,prices[i]-prices[i-1])return total
189. 旋转数组rotate array
将包含 n 个元素的数组向右旋转 k 步。
例如,如果 n = 7 , k = 3,给定数组 [1,2,3,4,5,6,7]
,向右旋转后的结果为 [5,6,7,1,2,3,4]
。
class Solution:def rotate(self, nums, k):""":type nums: List[int]:type k: int:rtype: void Do not return anything, modify nums in-place instead."""if k%len(nums)!=0:#整除则旋转一轮不变
这篇关于LeetCode初级算法练习——数组篇的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!