路径数组变为统计数组

/**
 * Created by lxw, liwei4939@126.com on 2017/11/5.
 * 路径数组变为统计数组
 * 给定一个路径数组paths,paths[i] == j表示城市i指向城市j,
 * 若paths[i] == i,则表示城市i是首都
 * 设计函数调整paths为统计数组nums,nums[i] == j表示距离为i的城市有j座
 * 首都的距离为1,即nums[0] ==1
 */
public class pathsToCount {

    public void pathsToDistances(int[] paths){
        int cap = 0;
        for (int i=0; i< paths.length; i++){
            if(paths[i] == i){
                cap = i;
            } else if(paths[i] > -1){
                int curI = paths[i];
                paths[i] = -1;
                int preI = i;
                while (paths[curI] != curI){
                    if(paths[curI] > -1){
                        int nextI = paths[curI];
                        paths[curI] = preI;
                        preI = curI;
                        curI = nextI;
                    } else {
                        break;
                    }
                }
                int value = paths[curI] == curI ? 0: paths[curI];
                while (paths[preI] != -1){
                    int lastPreI = paths[preI];
                    paths[preI] = --value;
                    curI = preI;
                    preI = lastPreI;
                }
                paths[preI] = --value;
            }
        }
        paths[cap] = 0;
    }

    public void distanceToNums(int[] disArr){
        for (int i=0; i< disArr.length; i++){
            int index = disArr[i];
            if(index < 0){
                disArr[i] = 0;
                while (true){
                    index = -index;
                    if(disArr[index] > -1){
                        disArr[index]++;
                        break;
                    } else {
                        int nextIndex = disArr[index];
                        disArr[index] = 1;
                        index = nextIndex;
                    }
                }
            }
        }
        disArr[0] = 1;
    }

    public void pathsToNums(int[] paths){
        if(paths == null || paths.length == 0){
            return;
        }
        // citiiesPath -> distanceArray
        pathsToDistances(paths);

        // distanceArray -> numArray
        distanceToNums(paths);
    }

    public static void main(String[] args){
        pathsToCount tmp = new pathsToCount();
        int[] paths = {9, 1, 4, 9, 0, 4, 8, 9, 0, 1};
        tmp.pathsToNums(paths);
        for (int lel : paths){
            System.out.print(lel + " ");
        }
        System.out.println();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值