[leetcode#69] SQRT (x)

Source: Internet
Author: User
Tags square root

problem:

Implement int sqrt(int x) .

Compute and return the square root of X.

conclusion for Binary Search problem:

Binary search is such a elegant the solving problems, you must master it!!!The problem could use binary search always possess following characteristics.1. We want to find an element in a series?(Kth element, Sqrt root ...)2. The series has certain properties, which we can base on one element's info to exclude the elements before or after it. 2.1 Find certain element E in a sorted array. If Nums[mid] < E, we can exclude nums[0] to Nums[mid]. 2.2 Find first bug version. Once A bug version appears, {All versions after it is bug version}.ifVersion[mid] is not a bug version, we can discard to the part from Version[0] to Version[mid].    ... In total, we can base on an element' s info, to infer the elements before and after it.During The search process, we should take care of following things:1. Overflow problem. It may happen at the place we checking the mid index, and it could happen when we check value.2. The mid element is the answer, you should clearly define the same as update front and end (exclude mid or not). The process to use Binary search.step1:ddentify The property, how can we use it?Step2:design the proper intial search boundary. What is the initial values of front and end?Step3: indentify the stop condition. Note:the Stop Condidation is a certain point, it could is {a succsive range}. (Where the answer is?) We can use the target to indenify the stop condidation.

ProblemAnalysis:

The question:search the sqrt of X.target:search an integer m from [0, X], whose value meet:   x<= m^2 and (m+1) ^2 > for each integer in [0, X],  iffor 2:the search boundary is [ 03:based on the tareget. The stop condition is "X/mid >= mid && x/(mid+1) < mid+1".

Wrong solution:

 Public classSolution { Public intMYSQRT (intx) {if(X < 0)            Throw NewIllegalArgumentException ("X is not allowed in negative!"); intFront = 0; intEnd =x;  while(Front <=end) {            intMID = front + (end-front)/2; if(Mid * mid = =x) {returnmid; } Else if(Mid * mid >x) {End= Mid-1; } Else{Front= Mid + 1; }        }        returnFront-1; }}

MistakeAnalysis:

submission Result:time Limit exceeded last executed input:2147483647The above solution has following problems:1. Even itTryto avoid the overflow when calculate mid index, it incurs overflow when Doing:mid* Mid = =x. note:always Write' * ' through '/' and write ' + ' through '-'.2. Wrong stop condition. Since the target meet "mid^2 <= x < (mid+1) ^2", it actually covers a succsive range of X.--------------------------------------------------------------------------------------------------------------- ---Fix Method forabove problems:intMID = front + (end-front)/2;if(X/mid >= mid && x/(mid+1) < mid+1) {...} Improvement:the initial font of sqrt problem could beintEnd = (X/2 + 1)

Solution:

 Public classSolution { Public intMYSQRT (intx) {if(X < 0)            Throw NewIllegalArgumentException ("X is not allowed in negative!"); if(x = = 0)            return0; intFront = 1; intEnd =x;  while(Front <=end) {            intMID = front + (end-front)/2; if(X/mid >= mid && x/(mid+1) < mid+1) {                returnmid; } Else if(Mid > x/mid) {End= Mid-1; } Else{Front= Mid + 1; }        }        return0; }}

[leetcode#69] SQRT (x)

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.