36. Enter the two linked lists to find their first common node.
Problem-solving ideas: Here is the two linked list of nodes are put into two stacks, so you can follow the way out of the stack to compare nodes, because the single-linked list as long as there is the same node, then the nodes are the same, so if the node is different from the stack, you can return the previously saved Commonnode variable, The value of such a variable is the first common node.
ImportJava.util.Stack;/*Public class ListNode {int val; ListNode next = null; ListNode (int val) {this.val = val; }}*/ Public classSolution { PublicListNode Findfirstcommonnode (ListNode pHead1, ListNode pHead2) {if(PHead1 = =NULL|| PHead2 = =NULL) return NULL; ListNode Commonnode=NULL; Stack<ListNode> S1 =NewStack<listnode>(); Stack<ListNode> s2 =NewStack<listnode>(); S1.push (PHEAD1); S2.push (PHEAD2); ListNode P1=PHead1; ListNode P2=pHead2; while(P1.next! =NULL) {S1.push (p1.next); P1=P1.next; } while(P2.next! =NULL) {S2.push (p2.next); P2=P2.next; } while(S1.peek () = =S2.peek ()) {Commonnode=S1.peek (); if(S1.peek ()! =NULL) S1.pop (); if(S2.peek ()! =NULL) S2.pop (); //if S1 or S2 is empty, just jump out of the loop . if(S1.empty () | |s2.empty ()) Break; } returnCommonnode; }}
37. Count the number of occurrences of a number in the sorted array.
Public classSolution { Public intGETNUMBEROFK (int[] Array,intk) {intLen =Array.Length; intFirst =-1; intLast =-1; intnum = 0; for(inti = 0; i < Len; i++){ if(Array[i] = =k) { First=i; Break; } } for(inti = len-1; I >= 0; i--){ if(Array[i] = =k) { Last=i; Break; } } //if first and last are-1, the proof array is not the same as K if(First! =-1 && Last! =-1) {num= Last-first +1; } Else{num= 0; } returnnum; }}
java--Sword Point Offer (8)