Coursera Algorithms week2 基础排序 练习测验: Permutation

题目原文:

Given two integer arrays of size n , design a subquadratic algorithm to determine whether one is a permutation of the other. That is, do they contain exactly the same entries but, possibly, in a different order.

本质上就是求两个数组排序后是否相等,鉴于本节课学的是选择、插入、希尔排序,就选个最不熟悉的希尔排序来实现吧

 1 import java.util.Arrays;
 2 
 3 public class PermutationArrays {
 4     private int[] a;
 5     private int[] b;
 6     private int n;
 7     PermutationArrays(int n, int[] a, int[] b){
 8         this.a = a;
 9         this.b = b;
10         this.n = n;
11     }
12     private boolean less(int v, int w){
13         return v < w;
14     }
15     private void exch(int[] a, int i, int j){
16         int t = a[i];
17         a[i] = a[j];
18         a[j] = t;
19     }
20     private void sortByShell(int n, int[] a){
21         int h = 1;
22         while(h < n/3){
23             h = 3*h + 1;
24         }
25         while(h>=1){
26             for(int i = h; i<n;i++){
27                 for(int j = i; j>=h && less(a[j],a[j-h]);j=j-h){
28                     exch(a,j,j-h);
29                 }
30             }
31             h = h/3;
32         }
33     }
34     public boolean isPermutation(){
35         sortByShell(n,a);
36         System.out.println(Arrays.toString(a));
37         sortByShell(n,b);
38         System.out.println(Arrays.toString(b));
39         for(int i=0;i<n;i++){
40             if(a[i] != b[i])
41                 return false;
42         }
43         return true;
44     }
45     public static void main(String[] args){
46         int[] a = {1,2,4,5,6,11,9,7,8,0};
47         int[] b = {0,9,8,7,6,5,4,3,2,1};
48         PermutationArrays pa = new PermutationArrays(10,a,b);
49         System.out.println(pa.isPermutation());
50     }
51 }

 

转载于:https://www.cnblogs.com/evasean/p/7220045.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值