初级算法 数组

 
alist = [0,0,0,1,1,1,2,2,3]
[]
 
def distinct(index, alist):
    if index < 0:
        print(alist, len(alist))
        return alist
    if alist[index] in alist[index+1:]:
        alist.pop(index)
    distinct(index-1, alist)
 
distinct(len(alist) - 1, alist)
[0, 1, 2, 3] 4
 
class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for index in range(len(nums)-1,-1,-1):
            print(index)
            if nums[index] in nums[index+1:]:
                nums.pop(index)
        return len(nums)
 
Solution().removeDuplicates([1,1,2])
2
1
0
2
 
# 买卖股票的最佳时间
 
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max = 0 
        for index in range(len(prices)-1):
            print(index)
            if prices[index] < prices[index+1]:
                max += prices[index+1] - prices[index]
        return max
 
Solution().maxProfit([7,1,5,3,6,4])
0
1
2
3
4
7
 
# 存在重复
 
def exist_duplicate(alist):
    for index in range(1, len(alist)):
        if alist[index] in alist[0:index]:
            return True
    return False
 
exist_duplicate([1,2,3,4,4])
True
posted @ 2019-10-30 10:44  眼镜儿  阅读(74)  评论(0编辑  收藏  举报