庞果网在线编程之数组排序ruby解答

来源:互联网 发布:linux 刻录光盘 编辑:程序博客网 时间:2024/04/27 23:00

题目地址:http://hero.pongo.cn/Question/Details?ID=94&ExamID=92


题目:

题目详情

本题来自caopengcs,只要你有兴趣,每个人都可以出题(出题入口在主页右侧边栏“贡献题目”->“我要发布”内),以下是题目详情:

给定一个包含1-n的数列,我们通过交换任意两个元素给数列重新排序。求最少需要多少次交换,能把数组排成按1-n递增的顺序,其中,数组长度不超过100。

例如:

原数组是3,2,1, 我们只需要交换1和3就行了,交换次数为1,所以输出1。

原数组是2,3,1,我们需要交换2和1,变成1,3,2,再交换3和2,变为1,2,3,总共需要的交换次数为2,所以输出2。



这个问题有些头疼,主要是不知到是否需要通过递归比较等找出每一种走法后再找出步数最少的方案来还是一开始就找一种交换最少的方案然后按照方案实现代码,思考再三,选择了后者。主要原因是考虑到这种算法效率高。但是非常失败,一开始并没有找到正确的方案。 刚开始几个测试还是能通过的,到了第五个就通不过了。因为这是方案问题。最后找到了代码中的方案。其实很简单,只需要保证每一步交换至少有一个数落在最终位置就可以了。方案有了,代码也就简单不少了。


class SwapSort  def initialize(array)    @array = array  end=begin  def min_swap_count    head = 0    tail = @array.count - 1    swap_count = 0    while head != tail do      if @array[head] == head + 1        head += 1        next      end      if @array[tail] == tail + 1        tail -= 1        next      end      swap_count += 1      @array[head], @array[tail] = @array[tail], @array[head]    end    swap_count  end=end  def min_swap_count    head = 0    tail = @array.count - 1    swap_count = 0    while @array[tail] != tail + 1 do      pos = @array.index(tail + 1)      @array[tail], @array[pos] = @array[pos], @array[tail]      swap_count += 1      tail -= 1      break if tail < 0     end    swap_count  endenddescribe SwapSort do   it "should got 1 when input array is [3,2,1] " do     SwapSort.new([3,2,1]).min_swap_count.should == 1  end  it "should got 2 when input array is [2,3,1]" do     SwapSort.new([2,3,1]).min_swap_count.should == 2  end  it "should got 0  when input array is [1,2,3,4]" do    SwapSort.new([1,2,3,4]).min_swap_count.should == 0  end    it "should got 1 when input array is [1,4,3,2]" do     SwapSort.new([1,4,3,2]).min_swap_count.should == 1  end  it "should got 2  when input array is [4,3,1,2]"do     SwapSort.new([3,4,1,2]).min_swap_count.should == 2  endend


原创粉丝点击