letcode 034 在排序数组中查找元素的第一个和最后一个位置

本文介绍了一种使用二分查找算法在已排序数组中查找特定目标元素首次与末次出现位置的方法。通过递归地调整搜索范围,该算法能有效定位元素,并返回其在数组中的起始和结束索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

34. 在排序数组中查找元素的第一个和最后一个位置

采用二分查找 ,轻松查出

/**
 * 
 */
package test;

/***
 * @author 18071
 * @Date 2019年2月25日 功能:
 ***/
public class test {
	public static void main(String args[]) {

		int[] nums = { 5, 5, 5, 5, 5, 5, 5, 7, 7, 8, 8, 10 };
		int target = 8;
		Solution s = new Solution();
		if (s.find(nums, target, 0, 11) != null) {
			System.out.println("w2222ow");
		} else {
			
		}
	}
}

class remm {
	public int t(int x) {
		if (x > 5) {
			return 5;

		} else if (x < 5) {

		}
		return 123;

	}
}

class Solution {

	public int[] find(int[] nums, int target, int low, int heigh) {
		int mid;
		mid = (low + heigh + 1) / 2;
		int templow=0;
		int tempheigh=0;

		if (target == nums[mid]) {

			templow = mid;
			tempheigh = mid;
			while (templow > 0) {

				templow--;

				if (nums[templow] != target) {
					templow++;
					System.out.println(templow + "is templow      " + nums[templow]);
					break;
				}
			}

			while (tempheigh < heigh) {
				System.out.println(tempheigh + "is tempheigh      " + nums[tempheigh]);
				tempheigh++;

				if (nums[tempheigh] != target) {
					tempheigh--;

					//
					break;
				}

			}
			System.out.println("100 行   " + templow + "  " + tempheigh);
			int[] rua = { templow, tempheigh };
			for (int i = 0; i < 2; i++) {
				System.out.println(rua[i]);
			}
			return rua;

		}

		 if (target < nums[mid] && target > nums[low]) {

			heigh = mid;

			  return find(nums, target, low, heigh);
		}

		 if (target > nums[mid] && target < nums[heigh]) {

			low = mid;

			   return find(nums, target, low, heigh);

		}
		 
		 
		 
		return null;
		

		

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值