列表中,不输基准基准、列表中

2023-09-03 04:08:20 作者:拱手江河讨你欢

返回从采访。我与你分享以及良好和precise答案是值得欢迎的。

的目的,你有一个静态方法,这个方法接收的IList< INT> 你有 找回您可以通过3 divise的价值观,使code。

约束: 原来的列表(主)具有堆栈上堆的参考和值, 其结果必然是收益(这是一个无效的方法)在同一个空间(堆),比原来的列表中。该溶液显示在这里是不正确的,因为在该方法中一个新的指针 栈+堆在方法域中创建。解决办法?

奖励:如何改变code接收不仅诠释,但浮点型,双...

 静态无效的主要(字串[] args)
    {
        IList的< INT>名单=新的名单,其中,INT>(){9,3,10,6,14,16,20};
        CanBeDivedByThree(名单);
    }

    静态无效CanBeDivedByThree(IList的< INT>名单)
    {
        名单=(由对列表中
                其中p%3 == 0
                排序依据p下降
                选择P).ToList< INT>();
    }
 

解决方案

这是毫无意义的内部存储到的IList 不是你的控制之下。添加(或可能删除)项目可能重新分配的内部数据结构。

中国银行现在存款利率是多少 2020年中国银行存款基准利率表

有特别意义的名单样品中含有的值的,当你访问它们这是无论如何都会被复制类型。

最后但并非最不重要它基本上是使用你不必担心内存(人)的位置托管语言的整点。这样的事情是实施细节平台。

要拿起你的奖金问题:有没有简单的方法来实现这一目标。人们可以认为,使用泛型与类型约束要在这里解决问题(像静态无效CanBeDivedByThree< T>(IList的< T>清单)其中T:结构),但问题是,C#不(没?)有通用算法的支持。 C#不有模运算符,可以采取类型'T'和'廉政'。

的泛型参数

Back from interview. I share with you and a good and precise answer is welcome.

The purpose, you have a static method, this method receive an IList<int> you have to get back the values you can divise by 3 and make the code.

Constraint : The original list (in the main) has a reference on the stack and the values on the heap, the result must be return (it's a void method) in the same space (on the heap) than the original list. The solution show here is not correct because in the method a new pointer on the stack + heap are created in the method domain. Solution ?

Bonus : how change the code to receive not only int but float, double, ....

static void Main(string[] args)
    {
        IList<int> list = new List<int>() { 9, 3, 10, 6, 14, 16, 20};
        CanBeDivedByThree(list);
    }

    static void CanBeDivedByThree(IList<int> list)
    {
        list = (from p in list
                where p % 3 == 0
                orderby p descending
                select p).ToList<int>();
    }

解决方案

That's meaningless as the internal storage to an IList is not under your control. Adding (or possibly removing) items might re-allocate the internal data structures.

It is especially meaningless as the list in your sample contains value types which are copied anyway when you access them.

Last but not least it's basically the whole point of using a managed language that you don't have to worry about memory (al)locations. Such things are implementation details of the platform.

To take up on your bonus question: There is no simple way to achieve that. One could think that using generics with a type constraint would solve the problem here (something like static void CanBeDivedByThree<T>(IList<T> list) where T : struct), but the problem is that C# does not (yet?) have support for generic arithmetic. C# doesn't have a modulo operator that can take a generic parameter of type 'T' and 'int'.