- 第217题(简单):Contains Duplicate
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数应该返回 true。如果每个元素都不相同,则返回 false。
思路:
-
字典法。建立一个字典,然后遍历数组中每一个数,如果这个数不在字典中,则把它加入字典中。
最后都不在,返回False。
如果在字典中,则返回True。 -
把数组从小到大排列,如果nums[i] == nums[i+1],则返回True。否则返回False。
代码1:
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 0:
return False
else:
dict = {}
for num in nums:
if num not in dict:
dict[num] = 1
else:
return True
return False
代码2:
class Solution:
def containsDuplicate(self, nums):
nums.sort()
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False
- 第219题(简单):Contains Duplicate II
Given an array of integers and an integer k,
find out whether there are two distinct indices
i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
找到最近的两个相同元素,并且这两个元素的角标的绝对值之差还要小于给定K。
注意:最近最近最近
注意:最近最近最近
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
dict = {}
for i, num in enumerate(nums):
if num not in dict:
dict[num] = i
else:
if i - dict[num] <= k:
return True
dict[num] = i
return False
- 第226题(简单). Invert Binary Tree 反转二叉树
Invert a binary tree.
Example:
Input:
Output:
思想:用递归的思想
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is not None:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
- 第231题(简单):Power of Two
Given an integer, write a function to determine if it is a power of two.
(1) Example 1:
Input: 1
Output: true
Explanation: 2^0 = 1
(2) Example 2:
Input: 16
Output: true
Explanation: 2^4 = 16
(3)Example 3:
Input: 218
Output: false
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n < 1:
return False
while n % 2 == 0:
n = n/2
if n == 1:
return True
else:
return False
- 第234题(简单):Palindrome Linked List 回文链表
Given a singly linked list, determine if it is a palindrome.
回文:从前读,和从后读,都一样
(1) Example 1:
Input: 1->2
Output: false
(2) Example 2:
Input: 1->2->2->1
Output: true
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow = fast = head
stack = []
while fast and fast.next:
stack.append(slow.val)
slow = slow.next
fast = fast.next.next
if fast: #单链表为奇数时,最后fast会存在
slow = slow.next
while slow:
top = stack.pop()
if top != slow.val:
return False
slow = slow.next
return True
- 第235题(简单): Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST),
find the lowest common ancestor (LCA) of two given nodes in the BST.
求二叉搜索树的最小共同父节点
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants
(where we allow a node to be a descendant of itself).”
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
(1) Example 1:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.
(2) Example 2:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2,
since a node can be a descendant of itself according to the LCA definition.
思路; 二分搜索树。就是根的左边数,都比根小。根的右边数,都比根大。
左<根<右
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
pointer = root
while pointer:
if p.val < pointer.val and q.val < pointer.val:
pointer = pointer.left
elif p.val > pointer.val and q.val > pointer.val:
pointer = pointer.right
else:
return pointer
- 第242题(简单):Valid Anagram
Given two strings s and t , write a function to determine if t is an anagram of s.
anagram:相同字母异序词
(1) Example 1:
Input: s = “anagram”, t = “nagaram”
Output: true
(2) Example 2:
Input: s = “rat”, t = “car”
Output: false
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
look_up = {}
for i in s:
if i not in look_up:
look_up[i] = 1
else:
look_up[i] += 1
for j in t:
if j not in look_up:
return False
else:
look_up[j] -= 1
for k in look_up:
if look_up[k] != 0:
return False
return True
- 第258题(简单) Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
给定一个非负整数,将该整数的所有数字的和作为新的整数,重复直至得到只有一个数的整数。
(1) Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
进一步:你能不用迭代或循环,在O(1)时间解决该问题吗?
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if num == 0:
return 0
else:
result = (num-1)%9 +1 #考虑到9的倍数,所以要-1。因为减了1,所以要加回去
return result
- 第263题(简单):Ugly Number 丑陋数
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers (正数) ,
whose prime factors only include 2, 3, 5.
这道题让我们检测一个数是否为丑陋数,所谓丑陋数就是其质数因子只能是2,3,5。
那么最直接的办法就是不停的除以这些质数,如果剩余的数字是1的话就是丑陋数了
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
for i in [2,3,5]:
while num % i == 0:
num /= i
return num == 1
- 第283题(简单):Move Zeros
给定一个数组nums,写一个函数,将数组中所有的0挪到数组的末尾,⽽维持其他所有非0元素的相对位置。
举例: nums = [0, 1, 0, 3, 12],
函数运⾏后结果为[1, 3, 12, 0, 0]
思路:设定一个临时变量k=0,遍历数组nums,将非零元素移动到nums[k]位置,同时k++。而后剩下的位置,就都是0。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
k = 0
for i in range(len(nums)):
if nums[i]: # 如果等于0,if 0 为假,不能进入判断
nums[k] = nums[i]
k += 1
for i in range(k,len(nums)):
nums[i] = 0