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

题目地址: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
  end
end

describe 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
  end
end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值