1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
example
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
code
class Solution(object):
def twoSum(self,nums,target):
nums_index_map = {}
for i in range(len(nums)):
pair_num = target - nums[i]
if pair_num in nums_index_map:
return [nums_index_map[pair_num],i]
nums_index_map[nums[i]] = i
raise Exception("pair not found")
2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself.
example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
code
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dump = cur = ListNode(0)
carry = 0
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
val = carry%10
carry /= 10
cur.next = ListNode(val)
cur = cur.next
return dump.next
3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
example
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
我的超时的辣鸡code
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
# 最大的子字符串的长度存储
max_len = 0
# 起始index
start_index = 0
# 当前子字符串的长度
currnet_len = 0
while start_index < len(s):
# 获取子串(仅仅包含当前的起始的字符)
sub_str = s[start_index]
currnet_len = len(sub_str)
# print sub_str
# 从起始的位置+1开始往后叠加
for j in xrange(start_index+1,len(s)):
# 当前的最新的字符
current_character = s[j]
# 从已经存在的子串中找是否包含最新的字符
pos = sub_str.find(current_character)
# 如果找到
if pos>-1:
# 更新起始位置为当前起始位置加上偏移量
start_index += (pos + 1)
# 更新最大长度
if currnet_len > max_len:
max_len = currnet_len
break
# 如果没找到
else:
# 更新子串
sub_str += current_character
currnet_len = len(sub_str)
if (start_index + max_len) >= len(s):
break
# 最后更新一次
if currnet_len > max_len:
max_len = currnet_len
return max_len
code
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
ans = 0
i = 0
j = 0
n = len(s)
str_dict = {}
while j<n:
if s[j] in str_dict:
i = max([str_dict[s[j]],i])
ans = max([ans,j-i+1])
str_dict[s[j]] = j + 1
j += 1
return ans
4. Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
example 1
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
example 2
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
code
too hare for me
5. Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
example
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Input: "cbbd"
Output: "bb"
code
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
res = ""
for i in xrange(len(s)):
# odd case, like "aba"
tmp = self.helper(s,i,i)
if len(tmp)>len(res):
res = tmp
# even case, like "abba"
tmp = self.helper(s,i,i+1)
if len(tmp)>len(res):
res = tmp
return res
def helper(self,s,l,r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return s[l+1:r]
6. ZigZag Conversion
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
example
P A H N
A P L S I I G
Y I R
code
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1 or numRows >= len(s):
return s
L = [''] * numRows
index, step = 0, 1
for x in s:
L[index] += x
if index == 0:
step = 1
elif index == numRows -1:
step = -1
index += step
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer. Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
example
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
code
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
# cmp 比较,大的话为1,小的话为-1,相等为0
s = cmp(x, 0)
# magic `` 符号,会把之类的变量转化为字符串
r = int(`s * x`[::-1])
# 数字 * False == 0, * True不改变原来的值
return s * r * (r < 2 ** 31)
8. String to Integer (atoi)
Implement atoi to convert a string to an integer.
example
無し
code
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if len(str) == 0 : return 0
ls = list(str.strip())
sign = -1 if ls[0] == '-' else 1
if ls[0] in "-+" : del ls[0]
ret, i = 0, 0
while i < len(ls) and ls[i].isdigit():
ret = ret*10 + int(ls[i])
i += 1
return max(-2**31, min(sign * ret, 2**31-1))
9. Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
example
無し
code
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
return `x` == `x`[::-1]
11. Container With Most Water
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not slant the container and n is at least 2.
example
無し
code
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
m,i,j = 0,0,len(height)-1
while i < j:
hi = height[i]
hj = height[j]
tmp = (j - i) * min(hi,hj)
m = max(m,tmp)
if hi > hj:
j -= 1
else:
i += 1
return m