庞果网在线编程之数组排序ruby解答
来源:互联网 发布:linux 刻录光盘 编辑:程序博客网 时间:2024/04/27 23:00
题目地址:http://hero.pongo.cn/Question/Details?ID=94&ExamID=92
题目:
题目详情
这个问题有些头疼,主要是不知到是否需要通过递归比较等找出每一种走法后再找出步数最少的方案来还是一开始就找一种交换最少的方案然后按照方案实现代码,思考再三,选择了后者。主要原因是考虑到这种算法效率高。但是非常失败,一开始并没有找到正确的方案。 刚开始几个测试还是能通过的,到了第五个就通不过了。因为这是方案问题。最后找到了代码中的方案。其实很简单,只需要保证每一步交换至少有一个数落在最终位置就可以了。方案有了,代码也就简单不少了。
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
- 庞果网在线编程之数组排序ruby解答
- 庞果网在线编程之最长有效括号长度问题ruby解答
- 庞果网在线编程字符串消除问题ruby解答
- 庞果网在线编程子序列的个数问题ruby解答
- C语言编程常见问题解答之数组
- 庞果网在线编程覆盖数字问题ruby答案
- Ruby之数组
- Ruby 如何排序Hash数组
- ruby 数组指定方式排序
- ruby 数组指定方式排序
- 庞果网之数组排序
- 庞果网建立基站问题ruby解答
- 庞果网回文数问题ruby解答
- Ruby学习之路——编程实践【3】 排序——快速排序
- 编程之美习题解答
- 赛码网-在线编程:翻转数组
- 在线编程--双栈排序
- 在线编程--小范围排序
- Xcode 4.3.2 (4E2002)错误提示Storyboards are unavailable on iOS 4.3 and prior的解决方法
- make xxx Is a directory. Stop. 的原因
- 快速求幂
- 转:雕爷口述:劈开脑海的黑魔法,宁当榴莲不做香蕉!
- Java基础知识学习二(数据类型及运算)
- 庞果网在线编程之数组排序ruby解答
- 使用vs1003制作MP3问题总结
- Eclipse/MyEclipse注释模板和格式化模板的使用
- 关于QueryParser类前后修改
- Python基于OpnenCV实现人脸识别
- 为老师分担任务
- URAL 1721 Two Sides of the Same Coin(二分匹配)
- 构建Maven本地仓库Nexus
- SPM:Spatial Pyramid Matching for Recognizing Natural Scene Categories 空间金字塔匹配