力扣(LeetCode)简单算法

  1. 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

来源:力扣(LeetCode)

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        for i in range(len(nums)):
            if nums[i] ==0:
                nums.remove(nums[i])
                nums.append(0)
        return nums
  1. 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
    最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
    你可以假设除了整数 0 之外,这个整数不会以零开头。

来源:力扣(LeetCode)

a= [1, 9,9,9,9] -
b = len(a)
if b ==1:
    if a[0] ==9:
        a[0]=0
        a.insert(0,1)
    else:
        a[0] +=1
else:
    a[-1] += 1
    for i in range(b):
        if a[b-1-i] ==10:
            a[b-1-i] =0
            a[b-2-i] +=1
        if a[0] == 10:
            a[0]=0
            a.insert(0,1)

print(a) #[2, 0, 0, 0, 0]

3.给定一个整数数组,判断是否存在重复元素。
如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。

来源:力扣(LeetCode)

class Solution (  ):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        a= False
        for i in range ( len ( nums ) - 1 ):
            for j in range ( i + 1, len ( nums ) ):
                # print(nums[i], nums[j])

                if nums[i] == nums[j]:
                    print(nums[i], nums[j])
                    a= True
                    break
                else:
                    pass
        return a

你可能感兴趣的:(力扣(LeetCode)简单算法)