首页 \ 问答 \ 这个解决方案对于Max Counters编码挑战有什么问题(What's wrong with this solution for Max Counters codility challenge)

这个解决方案对于Max Counters编码挑战有什么问题(What's wrong with this solution for Max Counters codility challenge)

所以我一直在通过关于编码的测试,并且与“Max Counters”之一卡住了(链接https://codility.com/demo/take-sample-test/max_counters )。 我的第一个明显的解决方案是以下一个:

def solution(N, A):

    counters = N * [0];    

    for a in A:
        if 1 <= a <= N:
            counters[a - 1] += 1;
        elif a == N + 1:
            counters = N * [max(counters)];

    return counters

它工作得很好,但花费了太多时间,因为每次调用max计数器都会填充整个数组。

因此,我想出了以下解决方案,对于小型输入似乎可以正常工作,但对大中型输入随机提供不正确的结果。

def solution(N, A):

    counters = N * [0];
    current_max = 0;
    last_update = 0;

    for a in A:
        if 1 <= a <= N:
            counters[a - 1] += 1;

            if counters[a - 1] < last_update:
                counters[a - 1] = last_update + 1;

            if counters[a - 1] > current_max:
                current_max = counters[a - 1];

        elif a == N + 1:
            last_update = current_max;

    for i in xrange(len(counters)):
        if counters[i] < last_update:
            counters[i] = last_update;           

    return counters

我似乎无法弄清楚它有什么问题。

编辑:结果 - http://codility.com/demo/results/demoQA7BVQ-NQT/


So I've been going through the tests on codility and got bit stuck with the "Max Counters" one (link https://codility.com/demo/take-sample-test/max_counters). My first, and obvious solution was the following one:

def solution(N, A):

    counters = N * [0];    

    for a in A:
        if 1 <= a <= N:
            counters[a - 1] += 1;
        elif a == N + 1:
            counters = N * [max(counters)];

    return counters

which works just fine, but takes too much time, due to the fact that each call to max counters fills an entire array.

So I came up with the following solution which seems to work ok for small inputs, but randomly provides incorrect results for medium and large ones.

def solution(N, A):

    counters = N * [0];
    current_max = 0;
    last_update = 0;

    for a in A:
        if 1 <= a <= N:
            counters[a - 1] += 1;

            if counters[a - 1] < last_update:
                counters[a - 1] = last_update + 1;

            if counters[a - 1] > current_max:
                current_max = counters[a - 1];

        elif a == N + 1:
            last_update = current_max;

    for i in xrange(len(counters)):
        if counters[i] < last_update:
            counters[i] = last_update;           

    return counters

I can't seem to figure out what's wrong with it.

Edit: Result - http://codility.com/demo/results/demoQA7BVQ-NQT/


原文:https://stackoverflow.com/questions/20506849
更新时间:2023-08-14 22:08

最满意答案

没有关于你的数据结构或你得到的错误的更多信息有点困难,你能否至少提供错误?

另外,你说你的LINQ语句应该“返回雇员”,但你把它作为“ViolationsDataSourceConfig”输入,这是如何工作的?

我首先想到的是LINQ语句默认会返回一个IEnumerable,所以它可能不会是正确的类型。

ppSource = (From a In application Where a.ApplicationID = ApplicationID And a.Status = 1 _
            Select a).FirstOrDefault()

可能会更接近你的目标...


It's a little hard without more information regarding your data structures or the errors you're getting, could you provide the error at least?

Also, you say your LINQ statement should "return employee" but you are typing it as "ViolationsDataSourceConfig", how does that work?

My first thought would be the LINQ statement will return an IEnumerable by default so it probably won't be the correct type.

ppSource = (From a In application Where a.ApplicationID = ApplicationID And a.Status = 1 _
            Select a).FirstOrDefault()

Might be closer to your goal...

相关问答

更多
  • 最简单的方法: var doNotMailIds = new HashSet(_doNotMailList.Select(x => x.id)); var mailItems = _mailList.Where(x => !doNotMailIds.Contains(x.id)); 假设你想要完整的Mail项目。 如果你只需要他们的ID,你可以在一个查询中完成: var mailIds = _mailList.Select(x => x.id) ...
  • DefaultIfEmpty具有带“默认”值的重载。 然后通过在DefaultIfEmpty之前添加Select ,您不需要检查null或创建s “空”实例 Dim avg = MyList.Where(Function(s) Month(s.Histo_Date) = Month(Date_Reference) - 1 AndAlso Year(s.Histo_Date) = Year(Date_Reference)). Select(Function(s) s.Nb_D ...
  • 将它包含在Take中。 (from workItem in WorkItem join workItemHistory in WorkItemHistory on workItem equals workItemHistory.WorkItem join ivSweepHistory in IVSweepHistory on workItemHistory equals ivSweepHistory.WorkItemHistory where workItem.SerialNumbe ...
  • 你真正想要的是源中的内容而不是(源中有什么而不是目标):S(S \ T)= S CUT T var result = from sourceWorkflow in sourceWorkflowList join targetWorflow in targetWorkflowList on new {sourceWorkflow.SubID, sourceWorkflow.ReadTime, sourceWorkflow.ProcessID, sou ...
  • 您可以从GameFormat表中获取GameDataID并使用它查询Game表 private Int64 GetGameID(string gameFormatProductCode) { ModelCtn ctn = new ModelCtn(); Game game = null; GameFormat gf = null; gf = (from t in ctn.GameFormat where t.GameFormatProductcode == ...
  • var res = items1.Where(a=> items2.Any(c=>c.Key == a.Key)); var res = items1.Where(a=> items2.Any(c=>c.Key == a.Key));
  • 没有关于你的数据结构或你得到的错误的更多信息有点困难,你能否至少提供错误? 另外,你说你的LINQ语句应该“返回雇员”,但你把它作为“ViolationsDataSourceConfig”输入,这是如何工作的? 我首先想到的是LINQ语句默认会返回一个IEnumerable,所以它可能不会是正确的类型。 ppSource = (From a In application Where a.ApplicationID = ApplicationID And a.Status = 1 _ ...
  • 从您提供的有限信息中很难说出来,但这可能会起到作用: var results = from stat in db.Stats group stat by stat.Date.Date into statGroup orderby statGroup.Key select new { Date = statGroup.Key, Maxi ...
  • 我试着用这种方式进行投射并且有效。 (from container in Container join containerType in ContainerType on container.ContainerType equals containerType where containerType.ContainerTypeID == 2 select container).Max (row => Convert.ToInt32(row.SerialNumber)) 但是,如果row.SerialNum ...
  • 首先让我说,如果这是您的要求......您的查询将读取数据库中的每条记录。 这将是一个缓慢的操作。 IQueryable query = db.Aspects.AsQueryable(); //note, if AllWords is empty, query is not modified. foreach(SearchAllWord x in AllWords) { //important, lambda should capture local variable instea ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)