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. MySQL 各级别事务的实现机制

    MySQL 各级别事务的实现机制在处理cnctp项目已合包裹状态同步的问题时,发现读包裹状态和对包裹状态的更新不在一个事务内,我提出是否会因为消息并发导致状态一致性问题.在和同事讨论的过程中,我们开始 ...

  2. SoapUI Pro Project Solution Collection-Custom project and setup

    import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.eviware.soap ...

  3. QT程序打包发布

    本来感觉这是一个简单的操作,今天看见群里有人在问这个问题,他说网上查了很多都不成功,突然就想把自己初学的时候记录一下! 题目谢了QT程序的打包发布,那就是两步骤:打包+发布! 注释:这篇博文用的是Qt ...

  4. Spring Boot 2.0 入门指南

    0x01 什么是Spring Boot? Spring Boot是用来简化Spring应用初始搭建以及开发过程的全新框架,被认为是Spring MVC的“接班人”,和微服务紧密联系在一起. 0x02 ...

  5. docker运行中的container怎么修改之前run时的env

    如题,这样: 1. service docker stop, 2. 修改/var/lib/docker/containers/[container-id]/config.json里对应的环境变量 3. ...

  6. js的new Date()日期的使用

    <script type="text/javascript"> //js获取某个月的天数 function days(year,month){ var dayCount ...

  7. 使用python抓取58手机维修信息

    之前在ququ的博客上看到说 python 中的BeautifulSoup 挺好玩的,今天下午果断下载下来,看了下api,挺好用的,完了2把,不错. 晚上写了一个使用python抓取58手机维修信息的 ...

  8. 导出不带.svn的文件夹或者是不含.class的文件

    转载自:http://blog.csdn.net/z278718149/article/details/21537395 如何导出不带.svn的文件夹或者是不含.class的文件 在工作环境中,有的时 ...

  9. bootstrap 3.0 LESS源代码浅析(二)

    border-radius是最常见的CSS3属性,但你知道他多少东西呢? 比如: border-radius:2em; 相当于什么? border-top-left-radius:2em; borde ...

  10. java InputStream和OutputStream

    InputStream类型 类 功能 构造器参数 如何使用 ByteArrayInputStream 允许将内存的缓冲区当做InputStreams使用 缓冲区,字节将从中取出 作为一种数据源:将其与 ...