Facebook面试题 Suffix array sorting

53 篇文章 0 订阅

Given a suffix array. E.g. int[] text = {10, 20, 30, 25}, then suffix[0] = {10, 20, 30, 25}, suffix[1] = {20, 30, 25}, succix[2] = {30, 25}, suffix[3] = {25}.
Then sort those arrays using lexical order. The result would be suffix[0] < suffix[1] < suffix[3] < suffix[2].

Implement the code to sort suffix array. Input: int[] text. Output: int[] sorted_suffix_array.
E.g. input: int[] text = {10, 20, 30, 25}, output: int[] sorted_suffix_array = {0, 1, 3, 2}.

  • Analysis:

    For this question, we need to sort a suffix arrays. In order to sort them, we need to compare each element. Thus we need to overwrite the comparator for sort.
    In order to sort them based on suffix arrays, we need to create a wrapper class storing the starting index and pointer to the text array. Thus we can use collections.sort()
    to sort this wrapper class.
    O(n) space. O((n ^ 2)logn) time ==> O(nlogn) sort, O(n) for each comparison, O(n * n logn) total.

Here is the implementation in Java:

public class Solution {
    class Suffix {
        int index;
        int[] array;

        public Suffix(int index, int[] array) {
            this.index = index;
            this.array = array;
        }
    }

    public int[] suffixSort(int[] text) {
        if (text == null || text.length == 0) return new int[]{};

        List<Suffix> suffixList = new ArrayList<>();
        for(int i = 0; i < text.length; i++) {
            suffixList.add(new Suffix(i, text));
        }

        int l = text.length;
        Collections.sort(suffixList, new Comparator<Suffix>() {
            @Override
            public int compare(Suffix s1, Suffix s2) {
                int i = 0;
                for(; i < Math.min(l - s1.index, l - s2.index); i++) {
                    if(s1.array[i] < s2.array[i]) {
                        return -1;
                    }
                    else if(s1.array[i] > s2.array[i]) {
                        return 1;
                    }
                }
                return i == l - s1.index ? -1 : 1;
            }
        });

        int[] ret = new int[l];
        int j = 0;

        for(Suffix s : suffixList) {
            ret[j++] = s.index;
        }

        return ret;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耀凯考前突击大师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值