1. Remove duplicates from the sorted array
Given a sorted array, you need to delete the repeating elements in place so that each element appears only once, returning the new length of the array after removal.
Instead of using extra array space, you must modify the input array in place and complete it with O (1) Extra space.
Note: is a sorted array
1 class Solution: 2 def removeduplicates (self,nums): 3 i =0 4while i < len (nums)-1:5 if nums[i+1] = = Nums[i]:6 nums.remove (nums[i+1])7 i +=1 8 return len (nums)
View Code
2. The best time to buy and sell stocks 2
Given an array, the first element of it is the price of the first day of a given stock.
Design an algorithm to calculate the maximum profit you can get. You can do as many trades as possible (buy and sell a stock).
Note: You cannot participate in multiple transactions at the same time (you must sell the prior stock before buying again).
Note: You cannot participate in multiple transactions at the same time
1 classSolution:2 defMaxprofit (self,prices):3 """4 : Type Prices:list[int]5 : Rtype:int6 """7sum =08 forIinchRange (1, Len (Prices)):9A = Prices[i]-prices[i-1]Ten ifA >0: Onesum = sum +a A returnSum
View Code
3. Rotating an array
Given an array, move the elements in the array to the right by the K position, where K is a non-negative
1 class Solution: 2 def Rotate (self,nums,k): 3 i =04 while I < K:5 nums.insert (0, Nums.pop ())6 i +=1
View Code
4. Duplication exists
Given an array of integers, determine if there are duplicate elements.
If any value occurs at least two times in the array, the function returns True. Returns False if each element in the array is not the same.
1 class Solution: 2 def containduplicate (self,nums): 3 NUMS1 =Set (nums)4 if len (nums1) = = Len (nums):5 return False 6 Else : 7 return True
View Code
Leetcode-Primary Array