Codility性能差异:数组与哈希

时间:2017-03-12 03:06:18

标签: ruby performance big-o

我在codility中进行了测试:https://codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/我注意到两种不同解决方案之间的性能差异:

1 - 列出解决方案:

public function assignlist( $status = "" ){
    $status1 = "Aktiv";
    if($status!=""){
        $status1 = $status; 
    }
    /* by Kenn */
    $log_in = $this->session->userdata('logged_in');
    $roleid = $log_in["role_id"];
    $CustomerID = $log_in["CustomerID"];
    /**/

    $this->datatables->select('er.EventId,er.EventName,cu.CustomerName as CustomerId,DATE_FORMAT(er.EventDate, "%d/%m/%Y") AS EventDate,er.TimeFrom,er.TimeTo,er.NoofGuardRequired,er.Remarks,emp.fullname as InsertBy,emp.fullname as ModifiedBy,er.Status,er.Status as st,cu.CustomerName as cuInsertBy, cu.CustomerName as cuModifiedBy');
    $this->datatables->from('eventregistration er'); 
    $this->datatables->join('customer cu', 'cu.CustomerId = er.CustomerId AND cu.CustomerId = er.InsertBy AND cu.CustomerId = er.ModifiedBy', 'left');
    $this->datatables->join('employee emp', 'emp.emp_id = er.InsertBy AND emp.emp_id = er.ModifiedBy', 'left');

    $this->datatables->where('er.Status',$status1);
    /* by Kenn */
    if ($roleid == "3"){
        $this->datatables->where('cu.CustomerID',$CustomerID);
    }
    /**/
    echo $this->datatables->generate();
}

2 - 哈希解决方案

def solution(list)
  unmatched_elements = []
  list.each{ |el|
    if unmatched_elements.include? el
      unmatched_elements.delete el
    else
      unmatched_elements.push el
    end
  }
  unmatched_elements[0]
end

第一个给了我25%的性能分数和一些超时。第二个给了我100%的表现分数。这是为什么?我想推哈希会导致O(n)空间复杂度像List一样,但它似乎不是,为什么?

1 个答案:

答案 0 :(得分:3)

这不是空间复杂性,而是时间复杂性。具体来说,查找数组中的元素(include?)是N次操作,因为它需要检查每个元素,直到匹配为止。散列查找[]是常量时间。

这个答案解释了为什么Hash有O(1)搜索时间:https://stackoverflow.com/a/4363602/1034681