java--Sword Point Offer (8)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.