数组编码和解码问题的求解设计与实现

来源:互联网 发布:华为网络培训资料 编辑:程序博客网 时间:2024/05/29 14:05

题目描述:

Java代码:

Code:
  1. package ttwork.lang;   
  2. import java.util.Arrays;   
  3.   
  4. public class TestFunnyArray {   
  5.     /*  
  6.      * 测试方法  
  7.      */  
  8.     public static void main(String[] args) {   
  9.         int[] a = {4,3,0,5,1,2};   
  10.         int[] b = {0,0,0,3,1,2};   
  11.         FunnyArray fa = new FunnyArray(a, FunnyArray1.SRCCODE);   
  12.         FunnyArray fb = new FunnyArray(b, FunnyArray1.DECODE);   
  13.         int[] c = fa.getDecodeBySrccode();   
  14.         System.out.println(Arrays.toString(c));   
  15.         int[] d = fb.getSrccodeByDecode();   
  16.         System.out.println(Arrays.toString(d));   
  17.     }   
  18. }   
  19.   
  20. class FunnyArray {   
  21.     private int[] srccode;   //源码   
  22.     private int[] decode;    //解码   
  23.     static final int SRCCODE = 8893939;   
  24.     static final int DECODE = 19494204;   
  25.     /*  
  26.      * 构造方法  
  27.      * @param1 :整型数组  
  28.      * @param2: 第二个参数用来表示已知的内容,源码还是解码  
  29.      */  
  30.     public FunnyArray(int[] code, int type) {   
  31.         if(type == SRCCODE) {   
  32.             srccode = code;   
  33.             decode = new int[srccode.length];   
  34.         }   
  35.         if(type == DECODE) {   
  36.             decode = code;   
  37.             srccode = new int[decode.length];   
  38.         }   
  39.     }   
  40.     /*  
  41.      * 求源码的方法  
  42.      * 对于解码,从后往前开始代表下标值,每加入一个就把这个值变成最大值排序,直到结束  
  43.      */  
  44.     public int[] getSrccodeByDecode() {   
  45.         int[] tempcode = new int[decode.length];   
  46.         for(int i=0; i<tempcode.length; i++) {   
  47.             tempcode[i] = i;   
  48.         }   
  49.         for(int i=decode.length-1; i>=0; i--) {   
  50.             srccode[i] = tempcode[decode[i]];   
  51.             tempcode[decode[i]] = Integer.MAX_VALUE;   
  52.             Arrays.sort(tempcode);   
  53.         }   
  54.         return srccode;   
  55.     }   
  56.     /*  
  57.      * 求解码的方法  
  58.      * 通过从开始查找到当前位置统计结果并赋值  
  59.      */  
  60.     public int[] getDecodeBySrccode() {   
  61.         int count;   
  62.         for(int i=0; i<srccode.length; i++) {   
  63.             count = 0;   
  64.             for(int j=0; j<i; j++) {   
  65.                 if(srccode[i] > srccode[j]) {   
  66.                     count ++;   
  67.                 }   
  68.             }   
  69.             decode[i] = count;   
  70.         }   
  71.         return decode;   
  72.     }   
  73. }