51.構建乘積數組
藉助兩個數組lefts和rights,一個記錄B[i]值的左乘結果A[0]*A[1]*...*A[i-1],一個記錄B[i]值的右乘結果A[i+1]*A[i+2]*...*A[n-1],然後B[i]=lefts[i]*rights[i];
import java.util.ArrayList;
public class Solution {
public int[] multiply(int[] A) {
int len = A.length;
int lefts[] = new int [len];
int rights[] = new int [len];
lefts[0]=lefts[len-1]=rights[0]=rights[len-1]=1;
for(int i =1;i<len;i++){
lefts[i] = A[i-1]*lefts[i-1];
}
for(int j = len-2;j>=0;j--){
rights[j] = A[j+1]*rights[j+1];
}
int B[] = new int[len];
for(int i=0;i<len;i++){
B[i]=lefts[i]*rights[i];
}
return B;
}
}
52.53,
54.字符流中第一個不重複的字符
用一個數組記錄出現的次數
並且每次把新加入的字符串添加到隊列中,在判斷的時候,直接從隊列開始處進行判斷,比較它的出現次數,如果符合則返回。
注意每一次都要新複製一個隊列,不可以在原隊列上修改。
import java.util.*;
public class Solution {
//Insert one char from stringstream
char res[] = new char [128];
Queue<Character> qu = new LinkedList();
public void Insert(char ch)
{
res[ch]++;
qu.add(ch);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
char res1 = '#';
Queue<Character> qu1 = new LinkedList(qu);
while(!qu1.isEmpty()){
char temp = qu1.remove();
if(res[temp]==1){
res1=temp;
break;
}
}
return res1;
}
}
55.鏈表中環的入口結點
畫一張圖,當兩個快慢結點相遇的時候,此時慢結點和一個從初始phead開始的新結點以相同的速度移動,二者會在環的入口處相遇。
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
if(pHead==null){
return null;
}
ListNode fast = pHead;
ListNode slow = pHead;
slow=slow.next;
if(slow==null){
return null;
}
fast=fast.next.next;
if(fast==null){
return null;
}
while(slow!=fast){
slow=slow.next;
fast=fast.next.next;
if(fast==null){
return null;
}
}
ListNode res = pHead;
while(slow!=res){
slow=slow.next;
res=res.next;
}
return res;
}
}