【发布时间】:2020-08-02 11:44:15
【问题描述】:
在一个竞争激烈的编码网站上,我遇到了这个问题。我能够使用以下代码解决基本用例的问题。但是,大输入超出了时间限制,我尝试减少循环次数,但仍然需要大约 2 秒的时间,但是限制只有 1 秒。
是否还有进一步优化此代码的空间?比如,我们可以删除嵌套循环吗?
static void Main(string[] args)
{
string[] first = (Console.ReadLine()).Split(null); //Sample input - 3 1 2 2 3
int N = int.Parse(first[0]);
int X = (int.Parse(first[1]) - 1);
int Y = (int.Parse(first[2]) - 1);
int Z = (int.Parse(first[3]) - 1);
int T = (int.Parse(first[4]) - 1);
string second = Console.ReadLine(); // Sample input - 1 2 3
List<int> list = new List<int>();
//Converting string inputs to int
list = second.Split().Select(str => int.Parse(str)).ToList();
List<int> xorList = new List<int>();
int xor = 0;
int temp = 0;
//Calculate the digits(using bitwise AND) of sub-matrix only, instead of entire matrix, and in the same loop, calculate bitwise XOR also.
for (int i = X; i <= Z; i++)
{
for (int j = Y; j <= T; j++)
{
temp = list[i] & list[j];
xor ^= temp;
}
}
Console.WriteLine(xor);
}
编辑:对于大型输入,矩阵的大小可以大到 100000 x 100000。 此外,数字序列可以包含大至 1000000000 的整数。
对于这样的整数,需要 2 秒。
【问题讨论】:
-
2 秒?对于这个简单的计算(假设样本输入)?你还计算编译时间吗?
-
@JHBonarius 先生,2 秒用于大输入。请参阅编辑。
标签: c# performance optimization bitwise-operators bitwise-xor