*牛客网面试高频题top100(1~10 java实现)
1.反转链表
描述:
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null) return null;
ListNode pre = null;
while(head!=null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
2.排序(快排)
描述:
给定一个长度为 n 的数组,请你编写一个函数,返回该数组按升序排序后的结果。
import java.util.*;
public class Solution {
public int[] MySort (int[] arr) {
if(arr.length==0) return arr;
QuickSort(arr,0,arr.length-1);
return arr;
}
public void QuickSort(int[] arr,int L,int r){
if(L<r){
int par = partition(arr,L,r);
QuickSort(arr,L,par);
QuickSort(arr,par+1,r);
}
}
public int partition(int[] arr,int L,int r){
int temp = new Random().nextInt(r-L+1)+L;
swap(arr,L,temp);
int key = arr[L];
while(L<r){
while(L<r && arr[r]>=key) r--;
arr[L] = arr[r];
while(L<r && arr[L]<=key) L++;
arr[r] = arr[L];
}
arr[L] = key;
return L;
}
public void swap(int[] arr,int i,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
归并排序实现:
import java.util.*;
public class Solution {
public int[] MySort (int[] arr) {
if(arr.length==0) return arr;
sort(arr,0,arr.length-1);
return arr;
}
// 归并排序
public void sort(int[] arr,int left,int right){
if(left>=right) return;
int mid = left +(right-left)/2;
sort(arr,left,mid);
sort(arr,mid+1,right);
merger(arr,left,mid,right);
}
public void merger(int[] arr,int left,int mid,int right){
int[] res = new int[right-left+1];
int k= 0, i=left, j=mid+1;
while(i<=mid && j<=right){
res[k++] = arr[i]<arr[j]?arr[i++]:arr[j++];
}
while(i<=mid){
res[k++] = arr