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;
}
}