您的位置:首页 > 其它

last position of target / first position of target

2016-12-13 10:27 281 查看
Last Position of Target

Find the last position of a target number in a sorted array. Return -1 if target does not exist.

O(log n)

public class Solution {
/**
* @param nums: An integer array sorted in ascending order
* @param target: An integer
* @return an integer
*/
public int lastPosition(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = (start + end) / 2;
if (target < nums[mid]) { //向后逼近
end = mid;
} else {
start = mid;
}
}
if (nums[end] == target) {
return end;
} else if (nums[start] == target) {
return start;
} else {
return -1;
}
}
}


First Position of Target

For a given sorted array (ascending order) and a 
target
number, find
the first index of this number in 
O(log n)
time complexity.

If the target number does not exist in the array, return 
-1
.

Example

If the array is 
[1,
2, 3, 3, 4, 5, 10]
, for given target 
3
, return 
2
.
O(log n)

class Solution {
/**
* @param nums: The integer array.
* @param target: Target to find.
* @return: The first position of target. Position starts from 0.
*/
public int binarySearch(int[] nums, int target) {
if(nums == null || nums.length == 0) {
return -1;
}
int start = 0, end = nums.length - 1;
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if(nums[mid] < target) { // 向前逼近
start = mid;
} else {
end = mid;
}
}
if(nums[start] == target) {//check the first position first
return start;
} else if(nums[end] == target) {
return end;
}
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  binary search