剑指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; } }
剑指Offer(四十):数组中只出现一次的数字
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param array int整型一维数组 * @return int整型一维数组 */ public int[] FindNumsAppearOnce (int[] array) { // write code here Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<array.length;i++){ if(map.containsKey(array[i])){ map.put(array[i],map.get(array[i])+1); }else{ map.put(array[i],1); } } int[] res=new int[2]; int index=0; for(Map.Entry<Integer,Integer> entry:map.entrySet()){ if(entry.getValue()==1){ res[index]=entry.getKey(); index++; } } return res; } }