搜索区间

给定一个包含 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());
    }
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值