LeetCode Start

LeetCode Start

由于想要提升自己的编程技巧和算法基础,为将来找工作做准备,所以现在开始每天至少刷一道题,请组织上监督我!

1. 如何高效地在LeetCode上面刷题

1.1 先用伪代码写出逻辑,再补全小段代码

力扣上面的Easy题分为两种,一种是不需要算法逻辑,只需要按照题目描述敲代码即可;另一种是套用标准算法即可。

其中第一类的Easy题,我们就可以采用先用伪代码写出逻辑,再补全小段代码。

方法:贪心
思路:首先假设使所有的人都去B面试,那么B处就多出了N个人, 此时需要选出N个人到达A处面试,这种方式对应的代价是cost_A - cost_B,这个值可正可负。因此我们需要选出对cost_A-cost_B进行排序,选出N个送到A。

例如 2020.08.27[001] 两地调度 问题:

class Solution:
    def twoCitySchedCost(self, costs):
        # Sort by a gain which company has 
        # by sending a person to city A and not to city B
      
        
  
        # To optimize the company expenses,
        # send the first n persons to the city A
        # and the others to the city B

补全后的代码为:

class Solution:
    def twoCitySchedCost(self, costs):
        # Sort by a gain which company has 
        # by sending a person to city A and not to city B
        costs.sort(key = lambda x : x[0] - x[1])
        
        total = 0
        n = len(costs) // 2
        # To optimize the company expenses,
        # send the first n persons to the city A
        # and the others to the city B
        for i in range(n):
            total += costs[i][0] + costs[i + n][1]
        return total

补充关于List的小语法:

list.sort(cmp=None, key=None, reverse=False)

  • cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
  • key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定 可迭代对象中的一个元素来进行排序。
  • reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。

1.2 判断题目描述是否满足某个算法所需的条件

刚开始我们可能会对题目应当用什么算法不太清楚,因此应该根据力扣上面的标签去做,然后分析题目和总结出规律。

例如,我们搜索二分查找问题,先从一道简单题开始。

2020.8.28 [002] 搜索插入位置问题:

分类:这道题属于典型的二分题目, 该题具有如下特点:

  • 数组是顺序的;
  • 答案是有界的,答案在[0, nums.size]之间;
  • 单调关系,目标值越大,答案越大

利用二分算法求解,需要注意到:

  • while(left < right) 表示结束时 left = right,因此取 left 和 right 都一样;
  • 下一次查找 [left, mid] 或 [mid+1, right],取决于目标值 target 是小于 mid 处的值还是大于 mid 处的值;
  • 同理,下一次查找[left, mid - 1] 或 [mid, right] 还是取决于目标值 target 是小于 mid 处的值还是大于 mid 处的值;
  • 如果每次查找的都是 [left, mid] 或 [mid+1, right]这一组,那么 mid 的计算方式是(left + right) // 2;
  • 如果每次查找的都是 [left, mid-1] 或 [mid, right]这一组,那么 mid 的计算方式是(left + right + 1) // 2;

思路:由于这道题不光要我们返回搜索到目标值的位置,如果没有搜索到还要返回要插入的位置。这个位置可能是 [0, nums.size] 中的任何一个值,所以我们只需要选出大于等于 target 的第一个位置,那么这个位置上的数值要么和 target 相等,则搜索到;要么是第一个大于target的位置,那么就应当把 target 插入在这。

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        left = 0
        right = len(nums) - 1
        ans = len(nums)

        while(left <= right):
            mid = (right + left) // 2
            if (nums[mid] >=  target):
                ans = mid
                right = mid - 1
            else:
                left = mid + 1
        return ans
原文地址:https://www.cnblogs.com/idella/p/13573983.html