【剑指offer】数组中的逆序对

【解题思路】

参照 --归并排序 

在前半部分和后半部分合并的时候,通过判断两个数组的最后位置数值的大小进行逆序对查找

firstHale[fst_end]>secHalf(sec_end)  说明对于firstHale[fst_end],后半部分数组都与之构成逆序对,直接压栈该数值对,

否则:

指向secHalf 的指针向前移动一步。

//temp 每次将比较结果中大的那个数字放入其中


【实现代码】

package offerExam;
import java.util.ArrayList;

class Pair{
	int bef;
	int beh;
	public Pair() {
		// TODO Auto-generated constructor stub
	}
}

public class InversePair {
public static void main(String[] args){
	ArrayList<Pair> pairList=new ArrayList<Pair>();
	int[] array={7,7,9,7,7};
	inversePair(array,pairList);
	System.out.println("there are "+pairList.size()+" pairs");
	print(pairList);
	
}
private static void print(ArrayList<Pair> pairList) {
	// TODO Auto-generated method stub
	if(pairList==null||pairList.isEmpty())
		{
		System.out.println("pairlist does not exist");
		return ;
		}
	for(int i=0;i<pairList.size();i++){
		System.out.print("("+pairList.get(i).bef+","+pairList.get(i).beh+") ");
	}
	
}

private static void inversePair(int[] array, ArrayList<Pair> pairList) {
	// TODO Auto-generated method stub
	if(array==null||array.length<=1||pairList==null)
		return;
	int fstLength=array.length/2;
	int[] fstHalf=new int[fstLength];
	System.arraycopy(array, 0, fstHalf, 0, fstLength);
	inversePair(fstHalf, pairList);
	
	int secLength=array.length-array.length/2;
	int[] secHalf=new int[secLength];
	System.arraycopy(array, fstLength, secHalf, 0, secLength);
	inversePair(secHalf, pairList);
	
	int[] temp=new int[array.length];
	generatePair(fstHalf,secHalf,pairList,temp);
	System.arraycopy(temp, 0, array, 0, array.length);
	
	
}

private static void generatePair(int[] fstHalf, int[] secHalf, ArrayList<Pair> pairList, int[] result) {
	// TODO Auto-generated method stub
	int fst=fstHalf.length-1;
	int sec=secHalf.length-1;
	int res=result.length-1;
	while(fst>=0&&sec>=0){
		
		if(fstHalf[fst]>secHalf[sec]){
			
			result[res--]=fstHalf[fst];
			
			addPair(fstHalf,fst,secHalf,sec,pairList);	
			fst--;
		}
	
		else{
			result[res--]=secHalf[sec];
			sec--;
			
		}
		
	}
	if(sec<0&&fst>=0)
	{
		for(int i=fst;i>=0;i--)
			result[res--]=fstHalf[i];
		
	}
	else if(sec>=0&&fst<0){
		for(int i=sec;i>=0;i--)
			result[res--]=secHalf[i];
	}
	
}

private static void addPair(int[] fstHalf, int fst, int[] secHalf, int sec, ArrayList<Pair> pairList) {
	// TODO Auto-generated method stub
	//将fstHalf 在fst中元素与secHalf 在索引0~sec之间的元素构成反转逆序对
	for(int i=sec;i>=0;i--)
	{
		Pair newPair=new Pair();
		newPair.bef=fstHalf[fst];
		newPair.beh=secHalf[i];
		pairList.add(newPair);
	}
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值