12/3

1、Two Sum

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for i in range(len(nums)):
j = target - nums[i]
if j in dict:
return [dict[j],i]
else:
dict[nums[i]] = i
#return 0

2. Add Two Numbers

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ans = 0
unit = 1
while l1 or l2:
if l1:
ans += l1.val * unit
l1 = l1.next
if l2:
ans += l2.val * unit
l2 = l2.next
unit *= 10 alpha = cur = ListNode(0) for n in reversed(str(ans)):
cur.next = ListNode(int(n))
cur = cur.next return alpha.next

补充:链表是由一些节点构成的,这些节点之间由指针连接,形成了一个链式结构。最基本的链表节点只需要存储当前节点的值,和一个指向下一节点的指针。由这种只存储下一节点地址的链表节点构成的链表被称为单向链表。

在节点ListNode定义中,定义为节点为结构变量。节点存储了两个变量:value 和 next。value 是这个节点的值,next 是指向下一节点的指针,当 next 为空指针时,这个节点是链表的最后一个节点。构造函数包含两个参数 _value 和 _next ,分别用来给节点赋值和指定下一节点。

struct ListNode {
int val; //定义val变量值,存储节点值
struct ListNode *next; //定义next指针,指向下一个节点,维持节点连接
}

203. Remove Linked List Elements( 类比 83. Remove Duplicates from Sorted List)

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head == None:
return head
dummy = ListNode(0)
dummy.next = head
pre = dummy
while head:
if head.val == val:
pre.next = head.next
head = pre
pre = head
head = head.next
return dummy.next

(链表)206. Reverse Linked List

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
tail = None
cur = head
while cur:
next_node = cur.next #存储当前节点的指向
cur.next = tail #当前节点指向尾节点,(改变指针指向)
tail = cur
cur = next_node
return tail

21. Merge Two Sorted Lists

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
cur = head while l1 and l2: if l1.val > l2.val:
cur.next = l2
l2 = l2.next else:
cur.next = l1
l1 = l1.next cur = cur.next cur.next = l1 or l2 return head.next

26. Remove Duplicates from Sorted Array

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cnt=0
if (len(nums)==0):
return cnt for i in sorted(set(nums)):
     #set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
nums[cnt]=i
cnt+=1 return cnt

27. Remove Element

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
index = 0
while(index < len(nums)):
if (nums[index] == val):
nums.pop(nums.index(val))
#pop()指定删除对象的索引位置,例如,a.pop(3)要删除列表a中索引3对应的元素。
else:
index += 1

88. Merge Sorted Array

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
for v in nums2:
nums1[m] = v
m+=1
nums1.sort()

(二叉树)111. Minimum Depth of Binary Tree

Given binary tree [3,9,20,null,null,15,7],

    3
/ \
9 20
/ \
15 7

return its minimum depth = 2.

class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0 children = [root.left, root.right]
# if we're at leaf node
if not any(children):
return 1 min_depth = float('inf')
for c in children:
if c:
min_depth = min(self.minDepth(c), min_depth)
return min_depth + 1

12/4

563. Binary Tree Tilt

Example:

Input:
1
/ \
2 3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
class Solution:
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.res = []
if not root:
return 0
self.dfs(root)
return sum(self.res)
def dfs(self,root):
if not root:
return 0
if not root.left and not root.right:
return root.val
leftsum = self.dfs(root.left)
rightsum = self.dfs(root.right)
self.res.append(abs(leftsum - rightsum))
return root.val + leftsum + rightsum

102. 二叉树的层次遍历

    3
/ \
9 20
/ \
15 7

return its level order traversal as:

[
[3],
[9,20],
[15,7]
]
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# write code here
if not root:
return []
queue=[root]
outList=[]
while queue:
res=[]
nextQueue=[]
for point in queue: #这里再遍历每一层
res.append(point.val)
if point.left:
nextQueue.append(point.left)
if point.right:
nextQueue.append(point.right)
outList.append(res)
queue=nextQueue #这一步很巧妙,用当前层覆盖上一层
return outList

83. Remove Duplicates from Sorted List

Input: 1->1->2->3->3
Output: 1->2->3
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
cur = head
while cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
continue
cur = cur.next
return head

237. Delete Node in a Linked List

 4 -> 5 -> 1 -> 9
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next

35. Search Insert Position

Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
index = 0
for i in nums:
diff = target - i
if diff > 0:
index += 1
else:
break
return index

724. Find Pivot Index

Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.
class Solution:
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lefty, righty = 0, sum(nums[1:])
if nums and lefty == righty:
return 0
for i in range(1, len(nums)):
lefty += nums[i-1]
righty -= nums[i]
if lefty == righty:
return i
return -1

674. Longest Continuous Increasing Subsequence

Input: [1,3,5,4,7]
Output: 3
class Solution:
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
dp[i] = dp[i - 1] + 1
return max(dp)
#返回最长序列的起始索引
#return dp.index(max(dp))-max(dp)+1

108. Convert Sorted Array to Binary Search Tree

class Solution:
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None mid = len(nums) // 2
#" // "来表示整数除法,返回不大于结果的一个最大的整数,而" / " 则单纯的表示浮点数除法 root = TreeNode(nums[mid])
root.left = self.sortedArrayToBST(nums[:mid])
root.right = self.sortedArrayToBST(nums[mid+1:]) return root

169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

Input: [3,2,3]
Output: 3
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = int(len(nums)/2)
b = collections.Counter(nums)
for i in nums:
if b[i]>a:
return i

242. Valid Anagram

Input: s = "anagram", t = "nagaram"
Output: true
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return collections.Counter(s) == collections.Counter(t)
#Counter(计数器)是对字典的补充,用于追踪值的出现次数。

283. Move Zeroes

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
i = 0
while i < length: if nums[i] == 0:
nums.append(nums.pop(i))
length -= 1
continue i += 1

268. Missing Number

Input: [9,6,4,2,3,5,7,0,1]
Output: 8
class Solution:
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length=len(nums)
return (int((length**2+length)/2))-sum(nums)

387. First Unique Character in a String

s = "loveleetcode",
return 2.
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
hash_table = {e:index for index, e in enumerate(s)} for index,e in enumerate(s):
if e in hash_table:
if hash_table[e]==index:
return index
del hash_table[e]
return -1

13. Roman to Integer

Symbol       Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Input: "III"
Output: 3
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dic = {'M':1000,
'D':500,
'C':100,
'L':50,
'X':10,
'V':5,
'I':1} temp = 0
res = 0
for c in s:
if dic[c] > temp:
res -= 2 * temp
temp = dic[c]
res += temp return res

350. Intersection of Two Arrays II

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
counts = collections.Counter(nums1)
res = [] for num in nums2:
if counts[num] > 0:
res.append(num)
counts[num] -= 1 return res

2019/3/29

28. 实现strStr()

(如何判断一个字符串是否包含另一个字符串)

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
m = len(haystack)
n = len(needle)
for i in range(m-n+1):
if haystack[i:i+n] == needle:
return i
return -1

26. 删除排序数组中的重复项

class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums) j = 0
for i in range(n-1):
if nums[i] == nums[i+1]:
nums[j] = nums[i] else:
nums[j] = nums[i]
nums[j+1] = nums[i+1]
j = j+1 return j+1

35. 搜索插入位置

class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
n = len(nums) if target > nums[n-1]:
return n
elif target < nums[0]:
return 0
for i in range(n):
while target == nums[i]:
return i
while target > nums[i] and target < nums[i+1]:
return i+1

7. 整数反转

class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
string = str(x)
if x < 0:
string = "-" + string[len(string):0:-1].lstrip("")
elif x > 0:
string = string[::-1].lstrip("")
else:
string = ""
if -2**31<int(string)<2**31-1:
return int(string)
else:
return 0
												

宝宝刷 leetcode的更多相关文章

  1. 刷LeetCode的正确姿势——第1、125题

    最近刷LeetCode比较频繁,就购买了官方的参考电子书 (CleanCodeHandbook),里面有题目的解析和范例源代码,可以省去非常多寻找免费经验分享内容和整理这些资料的时间.惊喜的是,里面的 ...

  2. 初刷LeetCode的感受

    自从上个月进入实验室的云安全项目组后,因为要接触到实际的代码,在实验室博士的建议下我们项目组的硕士开始刷LeetCode练习编程能力,保持每周抽空刷几道算法题.虽然刷的不多,到现在一共只刷了不到30题 ...

  3. 刷leetcode是什么样的体验?【转】

    转自:https://www.zhihu.com/question/32322023 刷leetcode是什么样的体验? https://leetcode.com/ 1 条评论   默认排序 按时间排 ...

  4. 用JavaScript刷LeetCode的正确姿势

    虽然很多人都觉得前端算法弱,但其实 JavaScript 也可以刷题啊!最近两个月断断续续刷完了 leetcode 前 200 的 middle + hard ,总结了一些刷题常用的模板代码.走过路过 ...

  5. 工具推荐--刷LeetCode的神器

    本文首发于微信公众号:[坂本先生],文章地址为: https://mp.weixin.qq.com/s/vHv5hO8nils_g2VSKwu1Cg如有转载请标明出处 今天给大家安利一款快速刷Leet ...

  6. 【一起刷LeetCode】整数反转

    前言&絮叨 别人都忙着参加年会晒奖品,我却忙着写代码.每逢年底都要安排几个紧急项目,我什么时候能摆脱这种宿命. 在忙也不能忘记刷LeetCode,毛毛向前冲!!! 题目描述 给出一个 32 位 ...

  7. 从心出发-刷leetcode写给5年后的自己

    而立之年终未立,不惑而年犹存惑!这或许就是所谓的中年危机吧! 自认为是一个"勤奋"的人,又"未有寸功",天天碌碌,不知何为. "常立志"而未 ...

  8. GitHub 热点速览 Vol.18:刷 LeetCode 的正确姿势

    作者:HelloGitHub-小鱼干 摘要:找对路子,事半功倍,正如本周 GitHub Trending #刷 LeetCode# 主题想表达的那般,正确的学习姿势方能让人走得更远,走进大厂

  9. 推荐一种通过刷leetcode来增强技术功底的方法

    背景 如果前人认为这个一种学习提高或者检验能力的成功实践.而自己目前又没有更好的方法,那就不妨试一试. 而不管作为面试官还是被面试者,编码题最近越来越流行.而两种角色都需要思考的问题是希望考察什么能力 ...

随机推荐

  1. sublime 3插件推荐

    新建文件以及快速注释 1.   SublimeTmpl 快速生成文件模板 一直都很奇怪为什么sublime text 3没有新建文件模板的功能,像html头部的DTD声明每次都要复制粘贴.用Subli ...

  2. 查看修改添加环境变量的工具——Rapid Environment Editor

    工欲善其事,必先利其器! 特别是公司或者有其他限制的时候,更需要一个比较简单.实用.强大的工具了! 原来的公司都是小公司,给电脑安装系统.软件等都是自己直接上手,现在在一个大点的公司了,电脑运维有单独 ...

  3. ARM与X86 CPU架构对比区别

    CISC(复杂指令集计算机)和RISC(精简指令集计算机)是当前CPU的两种架构.它们的区别在于不同的CPU设计理念和方法.早期的CPU全部是CISC架构,它的设计目的是  CISC要用最少的机器语言 ...

  4. 3.翻译系列:EF Code-First 示例(EF 6 Code-First系列)

    原文链接:http://www.entityframeworktutorial.net/code-first/simple-code-first-example.aspx EF 6 Code-Firs ...

  5. C#-MVC开发微信应用(4)--微信门户菜单的管理操作

    最近对微信接口进行深入的研究,通过把底层接口一步步进行封装后,逐步升级到自动化配置.自动化应答,以及后台处理界面的优化和完善上,力求搭建一个较为完善.适用的微信门户应用管理系统. 在微信门户系统里面, ...

  6. pandas DataFrame.shift()函数

    pandas DataFrame.shift()函数可以把数据移动指定的位数 period参数指定移动的步幅,可以为正为负.axis指定移动的轴,1为行,0为列. eg: 有这样一个DataFrame ...

  7. python和shell变量互相传递

    python -> shell: 1.环境变量 复制代码 代码如下: import os  var=123或var='123'os.environ['var']=str(var)  #envir ...

  8. [Big Data - Kafka] Kafka设计解析(三):Kafka High Availability (下)

    Kafka是由LinkedIn开发的一个分布式的消息系统,使用Scala编写,它以可水平扩展和高吞吐率而被广泛使用.目前越来越多的开源分布式处理系统如Cloudera.Apache Storm.Spa ...

  9. mysql 核心知识要点

    整体知识介绍:mysql基本操作和使用,mysql优化(索引,分表等),mysql部署(读写分离,负载均衡等) 数据库基本介绍:数据库概念,常用数据库,web应用三大软件分工,PHP动态语言特点(处理 ...

  10. headfirst python 01~02

    列表 列表就像是数组 在python 创建一个列表时, 解释器会在内存中创建一个类似数组的数据结构来存储数据, 数据项自下而上(形成一个堆栈), 类似于其他编程语言中的数组. 列表中常用方法: cas ...