给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
给出[5, 7, 7, 8, 8, 10]
和目标值target=8
,
返回[3, 4]
思想就是分布解答 ,针对数组为空的情况 返回【-1,-1】 数组中元素只有一个 或者数组中全部元素相同 记录count 利用Java的ArrayList判断 实现代码如下:(不考虑时间复杂度与空间复杂度)稍后麻烦 以后我会试着优化
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by JZloveSnow on 16/3/12.
*/
class Solution25 {
public int[] searchRange(int[] A, int target) {
if (A == null || A.length==0) {
// System.out.println("entering");
int[] res = new int[2];
res[0] = -1;
res[1] = -1;
return res;
}else {
// System.out.println("second");
List<Integer> array = new ArrayList<Integer>();
for (int i = 0; i < A.length; i++) {
array.add(A[i]);
}
int count=0;
int[] result = new int[2];
Iterator iterator = array.iterator();
for (int i=0; i<array.size(); i++) {
if (array.get(i) == target) {
count++;
}
}
if (count == array.size()) {
result[0] = 0;
result[1] = count-1;
return result;
}else {
for (int i = 0; i < array.size(); i++) {
if (array.contains(target)) {
result[0] = array.indexOf(target);
result[1] = array.lastIndexOf(target);
count++;
}else {
result[0] = -1;
result[1] = -1;
}
}
return result;
}
}
}
}
public class LC25 {
public static void main(String[] args) {
int[] A = {};
Solution25 solution25 = new Solution25();
System.out.println(solution25.searchRange(A, 8).toString());
}
}