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].
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# create a diction where the key is target-the_current_item and the value is the index of the item
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return sorted([i,buff_dict[nums[i]]])
else:
buff_dict[target - nums[i]] = i # dictionary look-up time is O(1)
# complexity O(n)

7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
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.

class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
isPos = cmp(x,0)
rev_num = int(`abs(x)`[::-1])
return isPos*rev_num*(rev_num<2**31) # backticks makes an object a string, equals to str()
# [::-1] reverses an string

9. Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
return `x` == `x`[::-1] # string is comparable using punc "=="
# negative integers can not be palindromes, et: -1
 

13. Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
""" roman_to_int = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
res = 0
pre = 0
for i in s[::-1]:
res = res + roman_to_int[i] if roman_to_int[i] >= pre else res - roman_to_int[i]
pre = roman_to_int[i]
return res # I = 1
# V = 5
# X = 10
# L = 50
# C = 100
# D = 500
# M = 1000
# travel backword would be much easier because there is only one situation we would use substraction

14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

 class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
return reduce(self.lcp,strs)
def lcp(self,str1,str2):
i=0
while(i<len(str1) and i<len(str2)):
if(str1[i]==str2[i]):
i=i+1
else:
break
return str1[:i] # do not neglect the situation when strs is an empty list
# lcp is an method of self, it's defined inside the class.

20. Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
brackets_dict = {']':'[' , '}':'{', ')':'('}
for elem in s:
if elem in brackets_dict.values():
stack.append(elem)
elif stack==[] or brackets_dict[elem] != stack.pop():
return False
if stack!=[]:
return False return True # consider what returns false:
# 1. not match
# 2. an right halve comes when the stack is empty
# 3. the stack is not empty when s is out of elements # always put isEmpty judge at the very begining
# python is capital sensitive, do not mistake true and false with True and False

26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
end_ind = 0
for i in range(1,len(nums)):
if nums[end_ind] != nums[i]:
end_ind += 1
nums[end_ind] = nums[i]
return end_ind+1 # ++ is illegal but += is not
# do not neglect the case when nums is an empty array

27. Remove Element

Given an array and a value, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if nums == []:
return 0
new = 0
for i in range(len(nums)):
if(nums[i] != val):
nums[new] = nums[i]
new += 1
return new # a plain answer

28. Implement strStr()

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == "":
return 0
ind = len(haystack)
while(needle in haystack[:ind]):
ind -= 1
return ind+1-len(needle) if ind != len(haystack) else -1 # if you want the index of the first occurence, you should do the delete_and_check backward
 

35. Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 1:

Input: [1,3,5,6], 0
Output: 0
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# one liner
return len([x for x in nums if x < target])

53. Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxsum=cursum=nums[0]
for i in nums[1:]:
cursum = max(cursum+i , i)
maxsum = max(cursum,maxsum)
return maxsum # treat the group as one element and compare it with the current element
# the current element would take place the whole group if it is more capable than the sum of the group

58. Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"
Output: 5
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.strip().split(' ')[-1])
# always come up with strip method when deal with last whitespace

557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
l = s.split(" ")
res = ""
for i in l:
res += i[::-1]+" "
return res.strip() # good solution from Jiale

67. Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if (len(a)==0):
return b
elif(len(b)==0):
return a
if(a[-1]=='1' and b[-1]=='1'):
return self.addBinary(self.addBinary(a[0:-1],b[0:-1]),'1')+'0'
elif(a[-1]=='0' and b[-1]=='0'):
return self.addBinary(a[0:-1],b[0:-1])+'0'
else:
return self.addBinary(a[0:-1],b[0:-1])+'1'
# recursive

69. Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

什么是牛顿法?

class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
r = x
while(r*r>x):
r = (r+x/r)/2
return r
# using Newton method

70. Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top. 1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
n_2 = 1
n_1 = 2
if n==1: return 1
if n==2: return 2
for i in range(n+1)[4:]:
n_1 += n_2
n_2 = n_1 - n_2
return n_2+n_1 # iteratively
# the finale step is either 1 or 2.
# From the point [n-1], we take one step to reach the point [n].
# From the point [n-2], we take a two-steps leap to reach the point [n]. 

83. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
root=head
while(head):
while(head.next and head.val == head.next.val):
head.next = head.next.next
head = head.next
return root # the second while loop will find the first element that is not the same with the current one until you come to the end of the list

88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

class Solution(object):
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.
"""
while(m>0 and n>0):
if(nums1[m-1]>=nums2[n-1]):
nums1[m+n-1] = nums1[m-1]
m -= 1
else:
nums1[m+n-1] = nums2[n-1]
n -= 1
if(n>0):
nums1[0:n] = nums2[0:n] return # be carefull when using slicing. The right index is not included. so you should just use the number of elements in this list. The slice will stop at the end of the list

136. Single Number

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?

class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x,y: x^y,nums) # exclusive OR, namely XOR

Leetcode with Python的更多相关文章

  1. LeetCode专题-Python实现之第28题: Implement strStr()

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  2. LeetCode专题-Python实现之第27题:Remove Element

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  3. LeetCode专题-Python实现之第26题:Remove Duplicates from Sorted Array

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  4. LeetCode专题-Python实现之第21题:Merge Two Sorted Lists

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  5. LeetCode专题-Python实现之第20题:Valid Parentheses

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  6. LeetCode专题-Python实现之第9题:Palindrome Number

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  7. LeetCode专题-Python实现之第14题:Longest Common Prefix

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  8. LeetCode专题-Python实现之第13题:Roman to Integer

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  9. LeetCode专题-Python实现之第7题:Reverse Integer

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  10. LeetCode专题-Python实现之第1题:Two Sum

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

随机推荐

  1. 一步一步教你玩转.NET Framework的配置文件app.config

    转自https://www.cnblogs.com/tonnie/archive/2010/12/17/appconfig.html 在一般的项目中,为了使你的代码更加灵活,更方便调整,减少不必要的h ...

  2. 洛谷 P1345 [USACO5.4]奶牛的电信Telecowmunication

    题目描述 农夫约翰的奶牛们喜欢通过电邮保持联系,于是她们建立了一个奶牛电脑网络,以便互相交流.这些机器用如下的方式发送电邮:如果存在一个由c台电脑组成的序列a1,a2,...,a(c),且a1与a2相 ...

  3. 如何将SAP Multi Target应用部署到SAP云平台的Cloud Foundry环境去

    SHINA是SAP HANA Interactive Education的缩写,是一个demo应用,用于演示如何开发SAP HANA原生应用. 这个应用包含了sample数据以及HANA数据库表,vi ...

  4. codeforce Gym 100500F Door Lock (二分)

    根据题意略推一下,其实就是问你满足(a*(a+1))/2 < m <= ((a+1)*a(a+2))/2的a和m-(a*(a+1))/2 -1是多少. 二分求解就行了 #include&l ...

  5. UVA12906 Maximum Score (组合)

    对于每个元素,最理想的情况就是都在它的左边或者右边,那么sort一下就可以得到一个特解了,然后大的中间不能有小的元素,因为如果有的话,那么无论选小的还是选大的都不是最优.对小的元素来说,比它大的元素在 ...

  6. [学习笔记] SSD代码笔记 + EifficientNet backbone 练习

    SSD代码笔记 + EifficientNet backbone 练习 ssd代码完全ok了,然后用最近性能和速度都非常牛的Eifficient Net做backbone设计了自己的TinySSD网络 ...

  7. ios常见错误之 Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?

    Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the desi ...

  8. hash join

    hash join是oracle里面一个非常强悍的功能,当做hash join时,oracle会选择一个表作为驱动表,先根据过滤条件排除不必要的数据,然后将结果集做成hash表,放入进程的hash a ...

  9. 数据结构实用C语言基础

    大纲: 主要介绍了C语言中的指针,内存分配,两种传参方式,typedef的简单用法 关于C语言中的指针: 指针变量也称为指针(Pointer) 例如:int* p; 则p为一个指向int类型的指针. ...

  10. MySQL在windows上的安装步骤

    参考文章MySQL安装及建议:https://zhuanlan.zhihu.com/p/44977117 但在进入mysql中修改root命令时,使用文章中的命令: ALTER USER 'root' ...