34. 在排序数组中查找元素的第一个和最后一个位置
class Solution {
private int[]num={-1,-1};
public int[] searchRange(int[] nums, int target) {
if(nums.length==0){
return num;
}
searchMin(nums,0,nums.length-1,target);
searchMax(nums,0,nums.length-1,target);
return num;
}
public void searchMin(int[] nums,int start,int end,int target){
if(start>end){
return ;
}
int middle=(start+end)/2;
if(nums[middle]==target){
num[0]=middle;
searchMin(nums,start,middle-1,target);
}
else if(nums[middle]>target){
searchMin(nums,start,middle-1,target);
}
else{
searchMin(nums,middle+1,end,target);
}
}
public void searchMax(int[] nums,int start,int end,int target){
if(start>end){
return ;
}
int middle=(start+end)/2;
if(nums[middle]==target){
num[1]=middle;
searchMax(nums,middle+1,end,target);
}
else if(nums[middle]>target){
searchMax(nums,start,middle-1,target);
}
else{
searchMax(nums,middle+1,end,target);
}
}
912. 排序数组–快速排序实现
class Solution {
public int[] sortArray(int[] nums) {
qSort(nums,0,nums.length-1);
return nums;
}
int[] qSort(int[] arr, int s, int e){
int low=s;
int height=e;
if (s>=e){
return arr;
}
int temp = arr[low];
while (low<height){
while (arr[height]>=temp&&height>low){
height--;
}
while (arr[low]<=temp&&height>low){
low++;
}
swap(arr,height,low);
}
swap(arr,low,s);
qSort(arr,s,low-1);
qSort(arr,low+1,e);
return arr;
}
private void swap(int[]arr,int i,int j){
int i1 = arr[i];
arr[i]=arr[j];
arr[j]=i1;
}
}
堆排序
public int[] heapSort(int[]arr){
int len=arr.length;
for (int i=len/2-1;i>=0;i--){
adjustHeap(arr,len,i);
}
for (int i=len-1;i>=0;i--){
swap(arr,0,i);
adjustHeap(arr,i,0);
}
return arr;
}
public void adjustHeap(int[]arr,int len,int index){
int left=2*index+1;
int right=2*index+2;
int temp=index;
if (left<len&&arr[left]>arr[temp]){
temp=left;
}
if (right<len&&arr[right]>arr[temp]){
temp=right;
}
if (temp!=index){
swap(arr,temp,index);
adjustHeap(arr,len,temp);
}
}