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