美文网首页
LeetCode.python.Array.1-5

LeetCode.python.Array.1-5

作者: 小异_Summer | 来源:发表于2018-03-27 19:17 被阅读0次

LeetCode.Array.easy

1. 1 TwoSum

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) <= 1:
            return False
        buf_dict = {}
        for i in range(0, len(nums)):
            if nums[i] in buf_dict:
                return [buf_dict[nums[i]], i]
            else:
                buf_dict[target-nums[i]] = i
        return False

2. 26 Remove Duplicates from Sorted Array

class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if (len(nums) == 0):
            return 0
        i = 0;
        for j in range(0, len(nums)):
            if (nums[j] != nums[i]):
                i += 1
                nums[i] = nums[j]
        return i + 1
class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums[:] = sorted(list(set(nums)))
        return len(nums)

3. 27. Remove Element

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i = 0
        for j in range(0, len(nums)):
            if (nums[j] != val):
                nums[i] = nums[j]
                i += 1
        return i;
class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        n = len(nums)
        i = 0
        while (i < n):
            if (nums[i] == val):
                nums[i] = nums[n-1]
                n -= 1
            else:
                i += 1
        return n

4. 35. Search Insert Position

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        low = 0
        high = len(nums)-1;
        while (low <= high):
            mid = int((low + high) / 2)
            if (nums[mid] == target):
                return mid;
            elif (nums[mid] > target):
                high = mid - 1
            else:
                low = mid + 1
        return low

5. 53 Maximum Subarray(类似于《剑指offer——连续子数组的最大和》)

class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sum_max = nums[0]
        sum_tmp = nums[0]
        for i in range(1, len(nums)):
            if (sum_tmp <= 0):
                sum_tmp = nums[i]
            else:
                sum_tmp += nums[i]
            sum_max = max(sum_max, sum_tmp)
            # print(i, sum_tmp, sum_max)
        return sum_max

相关文章

网友评论

      本文标题:LeetCode.python.Array.1-5

      本文链接:https://www.haomeiwen.com/subject/cgzjcftx.html