剑指Offer(三十五):数组中的逆序对
归并排序
public class Solution { public int InversePairs(int [] array) { if(array.length==0||array==null){ return 0; } int[] copyArray=new int[array.length]; int count=InversePairs(array,copyArray,0,array.length-1); return count; } public int InversePairs(int[] array,int[] copyArray,int low,int high){ if(low==high) return 0; int mid=low+(high-low)/2; int i=mid; int j=high; int localCopy=high; int count=0; int leftCount=InversePairs(array,copyArray,low,mid)%1000000007; int rightCount=InversePairs(array,copyArray,mid+1,high)%1000000007; while(i>=low&&j>mid){ if(array[i]>array[j]){ copyArray[localCopy--]=array[i--]; count+=j-mid; if(count>1000000007){ count=count%1000000007; } }else{ copyArray[localCopy--]=array[j--]; } } while(i>=low){ copyArray[localCopy--]=array[i--]; } while(j>mid){ copyArray[localCopy--]=array[j--]; } for(int k=low;k<=high;k++){ array[k]=copyArray[k]; } return (leftCount+rightCount+count)%1000000007; } }
剑指Offer(三十七):数字在排序数组中出现的次数
简单做法
public class Solution { public int GetNumberOfK(int [] array , int k) { int count=0; for(int i=0;i<array.length;i++){ if(array[i]==k){ count++; } } return count; } }
二分查找
二分查找,参考剑指Offer,但是用的非递归。 public class Solution { public int GetNumberOfK(int[] array,int k){ if(array==null||array.length==0) return 0; int first=getFirstK(array,k,0,array.length-1); int last=getLastK(array,k,0,array.length-1); if(first==-1 ||last==-1){ return 0; } else{ return last-first+1; } } public int getFirstK(int[] array,int k,int start,int end){ while(start<=end){ int mid=(start+end)/2; if(k<array[mid]) end=mid-1; else if(k>array[mid]) start=mid+1; else{ if((mid>0&&array[mid-1]!=k)||mid==0) return mid; else{ end=mid-1; } } } return -1; } public int getLastK(int[] array,int k ,int start,int end){ while(start<=end){ int mid=(start+end)/2; if(k<array[mid]) end=mid-1; else if(k>array[mid]) start=mid+1; else{ if((mid<array.length-1&&array[mid+1]!=k)||mid==array.length-1) return mid; else{ start=mid+1; } } } return -1; } }