题五十一 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
public class Solution {
public boolean isNumeric(char[] str) {
String res = String.valueOf(str);
boolean result = res.matches("[\\+-]?[0-9]*(\\.[0-9]+)?([eE][\\+-]?[0-9]+)?");
return result;
}
}
import java.util.*;
public class Solution {
HashMap<Character,Integer> map = new HashMap<>();
ArrayList<Character> list = new ArrayList<>();
//Insert one char from stringstream
public void Insert(char ch)
{
if(map.containsKey(ch)) map.put(ch,map.get(ch)+1);
else map.put(ch,1);
list.add(ch);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{ char res = '#';
for(char ch:list){
if(map.get(ch) == 1){
res = ch;
break;
}
}
return res;
}
}
题五十三 一个链表中包含环,请找出该链表的环的入口结点。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode meetingNode(ListNode head){
if(head == null || head.next == null) return null;
ListNode slow = head.next;
ListNode fast = slow.next;
while(slow != null && fast != null){
if(slow == fast) return fast;
slow = slow.next;
fast = fast.next;
if(fast != null) fast = fast.next;
}
return null;
}
public ListNode EntryNodeOfLoop(ListNode pHead)
{
ListNode meet = meetingNode(pHead);
if(meet == null) return null;
int cnt =1;
ListNode p1 = meet;
while(p1.next != meet){
p1 = p1.next;
cnt++;
}
p1 = pHead;
for(int i=0; i< cnt; i++){
p1 = p1.next;
}
ListNode p2 = pHead;
while(p1 != p2){
p1 = p1.next;
p2 = p2.next;
}
return p2;
}
}
题五十四 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead == null || pHead.next == null) return pHead;
ListNode tmp = new ListNode(-1);
tmp.next = pHead;
ListNode curr = pHead;
ListNode pre = tmp;
while(curr != null && curr.next != null){
ListNode nxt = curr.next;
if(curr.val == nxt.val){
while(nxt != null && curr.val == nxt.val) nxt = nxt.next;
pre.next = nxt;
curr = nxt;
}
else {
pre = curr;
curr = curr.next;
}
}
return tmp.next;
}
}
题五十五 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
if(pNode == null ) return null;
if(pNode.right != null){
pNode = pNode.right;
while(pNode.left != null) pNode = pNode.left;
return pNode;
}
while(pNode.next != null){
if(pNode == pNode.next.left ) return pNode.next;
pNode = pNode.next;
}
return null;
}
}
题五十六 请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
if(pRoot == null) return true;
return help(pRoot.left,pRoot.right);
}
boolean help(TreeNode left,TreeNode right){
if(left == null && right == null) return true;
if(left != null && right != null){
return(left.val == right.val && help(left.left,right.right)&&help(left.right,right.left));
}
return false;
}
}
题五十七 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
import java.util.ArrayList;
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer> > ();
if(pRoot == null) return result;
Deque<TreeNode> q = new LinkedList<TreeNode>();
q.offer(pRoot);
int layer = 0;
while(!q.isEmpty()){
layer++;
ArrayList<Integer> res = new ArrayList<Integer>();
int curr = 0, size = q.size();
if((layer &1 ) == 0){
Iterator<TreeNode> it = q.descendingIterator();
while(it.hasNext()){
res.add(it.next().val);
}
}else{
Iterator<TreeNode> it = q.iterator();
while(it.hasNext()){
res.add(it.next().val);
}
}
while(curr <size){
TreeNode node = q.poll();
if(node.left != null) q.offer(node.left);
if(node.right != null) q.offer(node.right);
curr++;
}
result.add(res);
}
return result;
}
}
题五十八 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
import java.util.ArrayList;
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer> > ();
if(pRoot == null) return result;
Deque<TreeNode> q = new LinkedList<TreeNode>();
q.offer(pRoot);
int layer = 0;
while(!q.isEmpty()){
layer++;
ArrayList<Integer> res = new ArrayList<Integer>();
int curr = 0, size = q.size();
Iterator<TreeNode> it = q.iterator();
while(it.hasNext()){
res.add(it.next().val);
}
while(curr <size){
TreeNode node = q.poll();
if(node.left != null) q.offer(node.left);
if(node.right != null) q.offer(node.right);
curr++;
}
result.add(res);
}
return result;
}
}
题五十九 请实现两个函数,分别用来序列化和反序列化二叉树
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
String Serialize(TreeNode root) {
if(root == null ) return "#,";
String res = root.val +",";
res += Serialize(root.left);
res += Serialize(root.right);
return res;
}
TreeNode Deserialize(String str) {
String[] values = str.split(",");
Queue<String> q = new LinkedList<>();
for(int i =0; i!= values.length;i++){
q.offer(values[i]);
}
return preOrder(q);
}
TreeNode preOrder(Queue<String> q){
String s = q.poll();
if(s.equals("#")) return null;
TreeNode node = new TreeNode(Integer.valueOf(s));
node.left = preOrder(q);
node.right = preOrder(q);
return node;
}
}
题六十 给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot == null || k <= 0) return null;
TreeNode p = pRoot;
Stack<TreeNode> stack = new Stack<>();
int cnt = 1;
while(p!= null || !stack.isEmpty()){
while(p!= null){
stack.push(p);
p = p.left;
}
TreeNode tmp = stack.pop();
if(cnt++ == k) return tmp;
p = tmp.right;
}
return null;
}
}
题六十一 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
import java.util.*;
public class Solution {
int cnt;
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11,new Comparator<Integer>(){
public int compare(Integer t1,Integer t2){
return t2.compareTo(t1);
}
});
public void Insert(Integer num) {
cnt++;
if((cnt & 1) == 0){
if(!maxHeap.isEmpty() && num < maxHeap.peek()){
maxHeap.offer(num);
num = maxHeap.poll();
}
minHeap.offer(num);
}else{
if(!minHeap.isEmpty() && num > minHeap.peek()){
minHeap.offer(num);
num = minHeap.poll();
}
maxHeap.offer(num);
}
}
public Double GetMedian() {
if(cnt == 0)
throw new RuntimeException("no available number");
double res;
if((cnt & 1)== 1) res = maxHeap.peek();
else res = (minHeap.peek() + maxHeap.peek())/2.0;
return res;
}
}
题六十二 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> res = new ArrayList<Integer>();
if(size == 0) return res;
Deque<Integer> deq = new LinkedList<Integer>();
for(int i=0; i<num.length; i++){
int begin = i-size +1;
if(deq.isEmpty()) deq.offerLast(i);
else if(begin > deq.peekFirst()) deq.pollFirst();
while((!deq.isEmpty())&& num[deq.peekLast()]<=num[i]){
deq.pollLast();
}
deq.offerLast(i);
if( begin>= 0) res.add(num[deq.peekFirst()]);
}
return res;
}
}
题六十三 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
boolean[] visited = new boolean[matrix.length];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if(searchFromHere(matrix,rows,cols,i,j,0,str,visited))
return true;
}
}
return false;
}
public boolean searchFromHere(char[] matrix, int rows, int cols, int r, int c, int index,char[] str,boolean[] visited){
if(r<0 || r>=rows || c<0 || c>=cols || matrix[r*cols+c]!=str[index] || visited[r*cols+c]) return false;
if(index == str.length -1) return true;
visited[r*cols+c] = true;
if(searchFromHere(matrix,rows,cols,r-1,c,index+1,str,visited)||
searchFromHere(matrix,rows,cols,r,c-1,index+1,str,visited)||
searchFromHere(matrix,rows,cols,r+1,c,index+1,str,visited)||
searchFromHere(matrix,rows,cols,r,c+1,index+1,str,visited))
return true;
visited[r*cols+c] = false;
return false;
}
}
题六十四 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{ if(threshold <0) return 0;
boolean [][]dp = new boolean[rows+1][cols+1];
dp[0][0] = true;
for(int i=1; i<=rows; i++){
if(dp[i-1][0] && reach(threshold,i,0)) dp[i][0] = true;
else dp[i][0] = false;
}
for(int i=1; i<= cols; i++){
if(dp[0][i-1] && reach(threshold,0,i)) dp[0][i] = true;
else dp[0][i] = false;
}
for(int i=1; i<= rows; i++){
for(int j=1; j<= cols; j++){
if((dp[i-1][j] && reach(threshold,i,j))||(dp[i][j-1] && reach(threshold,i,j))) dp[i][j] = true;
else dp[i][j] = false;
}
}
int cnt=0;
for(int i=0; i< rows; i++){
for(int j=0; j< cols; j++){
if(dp[i][j]) cnt++;
}
}
return cnt;
}
public boolean reach(int thr, int x, int y){
int sum = 0;
while(x>0){
sum += x%10;
x /= 10;
}
while(y>0){
sum += y%10;
y /= 10;
}
return sum <= thr;
}
}