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

版权声明:be the one ~you will be the one~~ https://blog.csdn.net/Hqxcsdn/article/details/87923244

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;
		

		

	}
}

猜你喜欢

转载自blog.csdn.net/Hqxcsdn/article/details/87923244