1.数组定义以及和列表、集合的区别
集合是一系列数据的合集,内部没有顺序,而列表则是拥有一定规则的集合,即内部数据拥有一定的顺序,数组则是更特殊一点的列表,其拥有索引,并且在内存中是连续存储的。
2.数组的中心索引
数组的中心索引实际上就是数组的一个下标,下标左侧的数据之和等于下标右侧的数据之和。
例如:[1,2,3,4,8,-2],该数组的中心下标就是3,即从左往右数第四个数据。
3.C#实现
思路:
首先计算出所有的数据之和,然后从前往后开始遍历数组,依次将递增的数组索引作为假设要寻找的中心索引,然后用数据和减去该索引之前的所有数据之和(即前侧数据和),然后检查剩下的除开该索引对应的数据是否与前侧数据和相等,如果相等则认为找到了中心索引,如果不等,则继续循环,直到找到或者循环结束为止。
代码:
public int PivotIndex(int[] nums)
{
int index = nums.Length;
int number = 0;
int numberTotal = 0;
int temp = 0;
for (int i = 0; i < index; i++)
{
numberTotal += nums[i];
}
for (int i = 0; i < index; i++)
{
for (int j = 0; j < i; j++)
{
number += nums[j];
}
if (number == numberTotal - number - nums[i])
{
return i;
}
number = 0;
}
return -1;
}
优化思路:
可将number加和移动到第一层循环中,然后利用循环自加的特性,在第n次循环中,只计算前n-1次循环之和,从而减少循环层数。
int index = nums.Length;
int number = 0;
int numberTotal = 0;
for (int i = 0; i < index; i++)
{
numberTotal += nums[i];
}
for (int i = 0; i < index; i++)
{
if (number == numberTotal - number - nums[i])
{
return i;
}
number += nums[i];
}
return -1;