1.Reverse Vowels of a String(345) leetcode链接
<p>Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y".
</p>
Python代码
def reverseVowels(s):
total_vowels = 'AEIOUaeiou' # 元音字母
list_s = list(s)
start = 0 # 列表开头
end = len(s)-1 # 列表末尾
while start < end:
if list_s[start] not in total_vowels: # 从列表首到尾,判断是否是元音字母,不是的index加1
start += 1
elif list_s[end] not in total_vowels: # 从列表尾到首,判断是否是元音字母,不是的index减一
end -= 1
else: # 当两边都是元音字母时交换
list_s[start], list_s[end] = list_s[end], list_s[start]
start += 1
end -= 1
return ''.join(list_s)
2.Nim Game(292) leetcode链接
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.
Python代码
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 != 0
3.Single Number(136)leetcode链接
Given an array of integers, every element appears twice except for one. Find that single one.
Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
解题思路:这题考的是位操作。只需要使用异或(xor)操作就可以解决问题。
异或操作的定义为:x ^ 0 = x; x ^ x = 0。用在这道题里面就是:y ^ x ^ x = y; x ^ x = 0;
举个例子:序列为:1122334556677。4是那个唯一的数,之前的数异或操作都清零了,之后的数:4 ^ 5 ^ 5 ^ 6 ^ 6 ^ 7 ^ 7 = 4 ^ ( 5 ^ 5 ^ 6 ^ 6 ^ 7 ^ 7 ) = 4 ^ 0 = 4。问题解决。
Python代码
def singleNumber(nums):
result = nums[0]
for i in nums[1:]:
result = result ^ i
return result
4.Sum of Two Integers(371)leetcode链接
Calculate the sum of two integers a and b, but you are not allowed to use the operator+and-.
Example:Given a = 1 and b = 2, return 3.
思路方法
既然不能使用加法和减法,那么就用位操作。下面以计算5+4的例子说明如何用位操作实现加法:1. 用二进制表示两个加数,a=5=0101,b=4=0100;2. 用and(&)操作得到所有位上的进位carry=0100;3. 用xor(^)操作找到a和b不同的位,赋值给a,a=0001;4. 将进位carry左移一位,赋值给b,b=1000;5. 循环直到进位carry为0,此时得到a=1001,即最后的sum。
上面思路还算正常,然而对于Python就有点麻烦了。因为Python的整数不是固定的32位,所以需要做一些特殊的处理,具体见代码吧。代码里的将一个数对0x100000000取模(注意:Python的取模运算结果恒为非负数),是希望该数的二进制表示从第32位开始到更高的位都同是0(最低位是第0位),以在0-31位上模拟一个32位的int。
Python代码
def getSum(a, b):
while b != 0:
carry = a & b
a = (a ^ b) % 0x100000000
b = (carry << 1) % 0x100000000
return a if a <= 0x7FFFFFFF else a | (~0x100000000+1)
5.Add Digits(258)leetcode链接
Given a non-negative integernum, repeatedly add all its digits until the result has only one digit.
For example:
Givennum = 38, the process is like:3 + 8 = 11,1 + 1 = 2. Since2 has only one digit, return it.
Follow up:Could you do it without any loop/recursion in O(1) runtime?
结果发现其是以9为周期
Python代码
def addDigits(num):
if not num:
return num
res = num % 9
return res if res else 9
6.Find the Difference(389)leetcode链接
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:s = "abcd"
t = "abcde"
Output:eExplanation:
'e' is the letter that was added.
Python代码
方法1:
def findTheDifference(s, t):
for letter in t:
if t.count(letter) > s.count(letter):
return letter
方法2:
def findTheDifference(s, t):
return (collections.Counter(t) - collections.Counter(s)).popitem()[0]
7.Delete Node in a Linked List(237)leetcode链接
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
Python代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
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