开发者

Rewrite the below code in the best optimized one [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

How to rewrite the below code in a better way as to give the best performance

private static void GetCount(int No, int[,] Positions)
        {
            List<int> lstRows = new List<int>();
            List<int> lstCols = new List<int>();
            int count = 0;       

            //Get the unique rows and columns
            for (int i = 0; i < Positions.Length / 2; i++)
            {
                if (!lstRows.Contains(Positions[i, 0])) lstRows.Add(Positions[i, 0]);
                if (!lstCols.Contains(Positions[i, 1])) lstCols.Add(Positions[i, 1]);
            }
            //get row count
            for (int i = 0; i < lstRows.Count; i++开发者_JS百科) count += 8;
            //get column count
            for (int i = 0; i < lstCols.Count; i++) count += 8;

            int output = No-count;

            Console.WriteLine(output);
        }

Invocation as GetCount(1, new int[,] { { 6, 3 } });


for (int i = 0; i < lstRows.Count; i++) count += 8;
for (int i = 0; i < lstCols.Count; i++) count += 8;

You're multiplying, so just use

count += 8 * (lstRows.Count + lstCols.Count);

This will reduce the complexity for your calculation from O(N) to O(1)


How about this one:

private static void GetBuildingCount1(int No, int[,] Positions)
{
    var lstRows = new HashSet<int>();
    var lstCols = new HashSet<int>();           

    //Get the unique rows and columns
    for (int i = 0; i < Positions.Length / 2; i++)
    {
        lstRows.Add(Positions[i, 0]);
        lstCols.Add(Positions[i, 1]);
    }

    var count = (lstRows.Count + lstCols.Count) * 8;

    var output = No-count;

    Console.WriteLine(output);
}

if you don't want to use loop and want to do it using pure lambda and linq(just for less code, not for performance):

private static void GetBuildingCount1(int No, int[,] Positions)
{
    var rows = Positions.Cast<int>().Where((p, i) => i % 2 == 0).Distinct().Count();
    var cols = Positions.Cast<int>().Where((p, i) => i % 2 == 1).Distinct().Count();
    var result = No - (rows + cols) * 8;
    Console.WriteLine(result);
}


Also replace

List<int> lstRows = new List<int>();
List<int> lstCols = new List<int>();

with

HashSet<int> lstRows = new HashSet<int>();
HashSet<int> lsTCols = new HashSet<int>();

without changing anything else. The contains checks would be O(1) instead of O(n).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜