Fastest algorithm for circle shift N sized array for M position

后端 未结 24 3049
温柔的废话
温柔的废话 2020-11-28 05:33

What is the fastest algorithm for circle shifting array for M positions?
For example, [3 4 5 2 3 1 4] shift M = 2 positions should be [1 4 3 4 5 2 3

24条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 06:05

    This algorithm runs in O(n) time and O(1) space. The idea is to trace each cyclic group in the shift (numbered by nextGroup variable).

    var shiftLeft = function(list, m) {
        var from = 0;
        var val = list[from];
        var nextGroup = 1;
        for(var i = 0; i < list.length; i++) {
            var to = ((from - m) + list.length) % list.length;
            if(to == from)
                break;
    
            var temp = list[to];
            list[to] = val;
            from = to;
            val = temp;
    
            if(from < nextGroup) {
                from = nextGroup++;
                val = list[from];
            }
        }
        return list;
    }
    

提交回复
热议问题