The first day of the arithmetic problem of "Jian Point offer"

Source: Internet
Author: User

According to the individual plan, starting from today to do "sword refers to offer" above the algorithm problem, the practice platform for the cattle network, the above for each problem has sufficient test examples, feeling is very good. Four questions were made this afternoon, respectively:

1. Depth of two fork tree (book 55)

The depth of the binary tree

Judging the Balanced binary tree

2. Number of occurrences in the array (book 56)

Two numbers that appear only once in an array

3. And for the number of S (Book 57 questions)

Consecutive positive sequence for s

and two numbers for s

4. Flip the string (book 58 questions)

Left rotation string

Flip word order Column

Binary tree types of problems in the Leetcode on many occasions, the point of the sword is relatively simple, this is no longer explained, only in the final post code, it is necessary to pay attention to judge the balance of the binary tree how to use a traversal to judge (using post-order traversal, from the leaf node upward judgment).

And for the number of S is the use of the idea of the pointers, but also relatively easy, so today's focus is the 2nd, 4 questions.

2. Number of occurrences of numbers in an array

Title Description: In an integer array, except for two digits, the other numbers appear two times. Please write the program to find the two only occurrences of the number. The required time complexity is O (n), and the spatial complexity is O (1).

The subject uses bit arithmetic, and leetcode on 137. The single number II is similar, and in the discuss has the big God to put out the solution and the mathematics explanation, the interested classmate may understand. Unlike Leetcode, there are two numbers that appear only once and are therefore more troublesome.

Idea: If you can divide the original array into two sub-arrays with only one number, you can derive these two numbers with an XOR operation. Each number in the array, from beginning to end, gets the XOR result of two occurrences of a number. Because these two numbers are different, the result of the XOR is certainly not 0, which means that at least one of the binary representations of the result number is 1. Find the position of the first 1 bit in the result number, as the nth bit, the number in the original array is divided into two sub-arrays by the nth bit is not 1, and the nth bit of each number in the first Subarray is 1, and the nth bit of each number in the second subarray is 0. In this way, the original array is divided into two sub-arrays, with only one number appearing once in each sub-array, and the other numbers appearing two times.

Implementation code:

1 //The num1,num2 are arrays of length 1, respectively. Outgoing Parameters2 //set Num1[0],num2[0] to return the result3  Public classSolution {4      Public voidFindnumsappearonce (int[] Array,intNum1[],intnum2[]) {5         intt = 0;//Results of the first round of XOR6          for(intN:array) {7T ^=N;8         }9         intFirstone =Findfirstone (t);//Find the position of first position 1TenNum1[0] = 0; OneNum2[0] = 0; A          for(intN:array) { -             if(IsBit1 (N,firstone)) {//Divide the array according to whether the nth bit is 1 -Num1[0] ^=N; the}Else{ -Num2[0] ^=N; -             } -         } +     } -      +      Public intFindfirstone (intt) { A         intFirst = 0; at          while((t & 1) = = 0 && First < 32) {//int type is 32-bit -t = t>>1; -first++; -         } -         returnFirst ; -     } in      -      Public BooleanIsBit1 (intNumintindexbit) { tonum = num >>Indexbit; +         return(num & 1) = = 1; -     } the}

4. Flipping a string

Title Description: Flip word order: Enter an English sentence, flip the order of the words in the sentence, but the order of the characters in the word does not change. For simplicity, punctuation is treated like ordinary letters. such as "I am a student.", the output is "student." A am I ". Left rotation string: Transfers several characters in front of the string to the end of the string. If you enter "ABCDEFG" and the number 2, the output is "Cdefgab".

This topic examines how the flexible use of string flip to deal with the new problem, the following gives the implementation of string flipping code, the code, the string is first converted to a character array and then operation.

1  Public voidReverseString (Char[] Array,intStartintend) {2     if(Start >=end)3         return;4      while(Start <end) {5         CharTMP =Array[start];6Array[start] =Array[end];7Array[end] =tmp;8start++;9end--;Ten     } One}

Ideas are as follows:

Flip the word order: first Flip all the characters in the sentence, such as "I am a student." Flip to get ". Tneduts a ma I" and then flip the words inside the sentence back to get "student." A am I " left rotation string: take" ABCDEFG " as an example, the string according to the n divided into two parts of each part of the first flip, get " Bagfedc " and then flip the entire string, get " Cdefgab "

The code is as follows:

Flip word order:

 Publicstring reversesentence (String str) {Char[] Array =Str.tochararray (); ReverseString (Array,0,array.length-1); ints = 0;  for(intend = 0; End < Array.Length; end++){            if(Array[end] = = ") {reversestring (Array,s,end-1); S= End+1; }} reversestring (Array,s,array.length-1); returnstring.valueof (array); }

Left rotation string:

 Public String leftrotatestring (String str,int  n) {        int len = str.length ();         if return str;         %= len;         Char [] array = str.tochararray ();        ReverseString (Array,0,n-1);        ReverseString (Array,n,len-1);        ReverseString (Array,0,len-1);         return string.valueof (array);    }

Finally, put the code for the 1th and 3rd questions:

Two-fork Tree:

//two depth of the fork tree Public classSolution { Public inttreedepth (TreeNode root) {if(Root = =NULL)            return0; intleft =treedepth (Root.left); intright =treedepth (root.right); returnMath.max (left,right) +1; }}//Judging the balanced binary tree Public classSolution { Public Booleanisbalanced_solution (TreeNode root) {if(Root = =NULL)            return true; returnMaxDepth (root)! =-1; }         Public intmaxDepth (TreeNode node) {if(node = =NULL)            return0; intleft =maxDepth (Node.left); intright =maxDepth (node.right); if(left = =-1 | | right =-1 | | Math.Abs (left-right) > 1){            return-1; }        returnMath.max (left,right) +1; }}

And for the number of S:

//and two numbers for SImportjava.util.ArrayList; Public classSolution { PublicArraylist<integer> Findnumberswithsum (int[] Array,intsum) {ArrayList<Integer> res =NewArrayList (); if(Array.Length = = 0)returnRes; intHead = 0, tail = array.length-1;  while(Head <tail) {            intp =Array[head]; intQ =Array[tail]; if(P+q = =sum)                {Res.add (P);                Res.add (q);  Break; }Else if(P+q >sum) {Tail--; }Else{Head++; }        }        returnRes; }}//consecutive positive sequence for SImportjava.util.ArrayList; Public classSolution { Publicarraylist<arraylist<integer> > Findcontinuoussequence (intsum) {        intsmall = 1, big = 2, mid = (sum+1)/2; ArrayList<ArrayList<Integer>> res =NewArrayList (); ArrayList<Integer> tmp =NewArrayList ();        Tmp.add (small);        Tmp.add (big); intTotal = small+Big;  while(Small <mid) {            if(Total = =sum) {Res.add (NewArrayList (TMP)); }            if(Total >sum) { Total-=Small; Small++; Tmp.remove (0); }Else{Big++; Total+=Big;            Tmp.add (big); }        }        returnRes; }}

The first day of the arithmetic problem of "Jian Point offer"

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.