如何优化遍历数组的循环? [英] How to optimize a loops going through arrays?

查看:81
本文介绍了如何优化遍历数组的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在访问 www.testdome.com 来测试我的技能并打开了一个公开问题列表.练习题之一是:

I've been going though www.testdome.com to test my skills and opened a list of public questions. One of the practice questions was:

实现函数 CountNumbers 接受排序数组整数并计算小于的数组元素的数量参数lessThan.

Implement function CountNumbers that accepts a sorted array of integers and counts the number of array elements that are less than the parameter lessThan.

例如,SortedSearch.CountNumbers(new int[] { 1, 3, 5, 7 }, 4)应该返回 2,因为有两个小于 4 的数组元素.

For example, SortedSearch.CountNumbers(new int[] { 1, 3, 5, 7 }, 4) should return 2 because there are two array elements less than 4.

我的回答是:

using System;

public class SortedSearch
{
    public static int CountNumbers(int[] sortedArray, int lessThan)
    {
        int count = 0;
        int l = sortedArray.Length;

        for (int i = 0; i < l; i++) {
            if (sortedArray [i] < lessThan)
                count++;
        }

        return count;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(SortedSearch.CountNumbers(new int[] { 1, 3, 5, 7 }, 4));
    }
}

我似乎在两个方面失败了:

It seems that I've failed on two counts:

sortedArray 包含 lessThan 时的性能测试:超出时间限制

sortedArray 不包含 lessThan 时的性能测试:超出时间限制

老实说,我不确定在那里优化什么?也许我使用了错误的方法,并且有类似的方法可以加快计算速度?

To be honest I'm not sure what to optimize there? Maybe I'm using a wrong method and there is a similar way to speed up the calculation?

如果有人能指出我的错误或解释我的错误,我将不胜感激!

If someone could point out my mistake or explain what I'm going wrong, I'd really appreciate it!

推荐答案

因为数组是排序的,所以只要达到或超过 lessThan 参数就可以停止计数.

Because the array is sorted, you can stop counting as soon as you reach or exceed the lessThan parameter.

else break 可能会这样做.

这篇关于如何优化遍历数组的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆