102 二叉樹層序遍歷 迭代
隊列的dfs經典問題
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
res, cur_level = [], [root]
while cur_level:
next_level, tmp_res = [], []
for node in cur_level:
tmp_res.append(node.val)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
res.append(tmp_res)
cur_level = next_level
return res
34,在排序數組中找到第一個和最後一個位置
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
雙指針發(可行):雙指針left和right分別指向數組的起始,即left = 0,right = nums.length - 1,之後,先從左向右遍歷,找到第一個nums[i] = target,left = i, 此時left爲左邊界;接着再從右向左遍歷,找到第一個nums[i] = target,right = i,此時right爲右邊界。
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
arr=[-1,-1]
if not nums:
return arr
left=0
right=len(nums)-1
while left<=right:
if nums[left]==target:
arr[0]=left
break
else:
left+=1
while left<=right:
if nums[right]==target:
arr[1]=right
break
else:
right-=1
return arr
33,在旋轉排序數組中找目標值
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
二分法
#coding:utf8
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
l=len(nums)
left=0
right=l-1
while left<=right:
m=(left+right)/2
if nums[m]==target:
return m
if nums[m]<nums[right]: #此時m到right升序,如果target在這區間等於號是細節
if target>nums[m] and target<=nums[right]:
left=m+1
else:
right=m-1
else: #此時left到m升序
if target<nums[m] and target>=nums[left]:
right=m-1
else:
left=m+1
return -1
最長迴文子串
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
class Solution {
public String longestPalindrome(String s) {
if(s.length()==1)return s;
int max=0;
String res=new String();
for (int i=0;i<s.length();i++){
int L=i;//aba
int R=i;
String temp=getPlength(s,L,R);
if(temp.length()>max){
max=temp.length();
res=temp;
}
if(i !=s.length()-1){
L=i;R=i+1;//abba
temp=getPlength(s,L,R);
if (temp.length()>max){
max=temp.length();
res=temp;
}
}
}
return res;
}
private String getPlength(String s,int L,int R){
while (L>=0 && R<s.length() && s.charAt(L)==s.charAt(R)){
L--;R++;
}
return s.substring(L+1,R);
}
}
11,容器的最大面積
/*用兩個指針從兩端開始向中間靠攏,如果左端線段短於右端,那麼左端右移,反之右端左移,知道左右兩端移到中間重合,記錄這個過程中每一次組成木桶的容積,返回其中最大的。當左端線段L小於右端線段R時,我們把L右移,這時捨棄的是L與右端其他線段(R-1, R-2, ...)組成的木桶,這些木桶是沒必要判斷的,因爲這些木桶的容積肯定都沒有L和R組成的木桶容積大。*/
import java.util.*;
class Solution {
public int maxArea(int[] height) {
int max=0;
int len=height.length;
int left=0;
int right=len-1;
while (left<right){
max=Math.max(max,Math.min(height[left],height[right])*(right-left));
if(height[left]<height[right]){
left++;
}else {
right--;
}
}
return max;
}
}