zoukankan      html  css  js  c++  java
  • 根据上排给出十个数,在其下排填出对应的十个数 要求下排每个数都是先前上排那十个数在下排出现的次数。

    腾讯面试题: 
    给你10分钟时间,根据上排给出十个数,在其下排填出对应的十个数 
    要求下排每个数都是先前上排那十个数在下排出现的次数。 
    上排的十个数如下: 
    【0,1,2,3,4,5,6,7,8,9】

    举一个例子, 
    数值: 0,1,2,3,4,5,6,7,8,9 
    分配: 6,2,1,0,0,0,1,0,0,0 
    0在下排出现了6次,1在下排出现了2次, 
    2在下排出现了1次,3在下排出现了0次.... 
    以此类推..

    a = [0,1,2,3,4,5,6]
    b = Array.new(a.length,0)
    
    #p a.repeated_combination(2).to_a
    
    def get_index_arr len,n  
      temp = []
      1.upto(len){|index| temp<<index}
      if n>len and len > 0
        temp << n
      end
      temp
    end
    
    def all_possible_arr arr, length
        ret = []
        length.times do
            if ret.empty?
                ret = arr.map {|i| [i]}      
            else
                new_ret = []
                ret.each do |r|
                    arr.each do |e|
                        new_ret << r.clone.unshift(e)
                    end
                end      
                ret = new_ret    
          #p ret      
            end
        end
        ret
    end
    
    def valid? arr
      arr.each_with_index do |v, i|
        return false if arr.select {|j| j == i}.size != v
      end
      true
    end
    
    def get_arr a,b
      for i in 0..a.length-1
        b[0] = i
        len = b.length-2-i
        temp = get_index_arr len,i
        l = temp.length
        sum = a.length - i
        return if l==0
        l_ = (sum.to_f/l).ceil
        temp_ = []
        1.upto(l_){|index| temp_ << index}
        all = all_possible_arr temp_,l
        #all = temp_.repeated_permutation(l).to_a
        all.each{|arr|
          if arr.inject(&:+) == sum        
            temp.each_index{|t|
              b[temp[t].to_i] = arr[t]          
            }        
            if valid? b
              p b
              return
            else
              b = Array.new(a.length,0)
              b[0] = i
            end
          end
        }
      end
    end
    get_arr a,b
  • 相关阅读:
    iOS 谁说程序猿不懂浪漫之 爱心
    iOS 星星评价视图 3行搞定
    iOS 柱状图的定制
    iOS 跑马灯 一句话集成
    代理的使用
    发送的网络请求中含有中文 转码的实现
    杂记
    使用纯代码实现UICollectionView(UITableView)需要注册
    NSASSert的使用
    iOS进阶第三节 数据处理之CoreData
  • 原文地址:https://www.cnblogs.com/zhangfei/p/3332839.html
Copyright © 2011-2022 走看看