Lintcode457. classic binary search problem, lintcode457 binary

Source: Internet
Author: User

Lintcode457. classic binary search problem, lintcode457 binary

[One click] errors reported countless times

One-sentence approach: Perform binary search for ordered Integers

Problem:

Format:

Conclusion: To clarify the relationship between the badge and the number, first define the badge, and finally return the badge

Public class Solution {
/*
* @ Param nums: An integer array sorted in ascending order
* @ Param target: An integer
* @ Return: An integer
*/
Public int findPosition (int [] nums, int target ){
// Write your code here
If (nums. length = 0 ){
Return-1;
}

Int start = 0;
Int end = nums. length-1;
Int mid;

While (start + 1 <end ){
Mid = start + (end-start)/2;
If (nums [mid] = target ){
End = mid;
} Else if (nums [mid] <target ){
Start = mid;
} Else if (nums [mid]> target ){
End = mid;
}
}

If (nums [start] = target ){
Return start;
}
If (nums [end] = target ){
Return end;
}
Return-1;
}
}

The parallel structure is edited successively. It is best to separate it:

if (nums[start] == target){            return start;        } if (nums[end] == target){            return end;        }

 

Related Article

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.