// 数组比List还要慢一点(10%以内) static int GetMinPlusSum_nlogn_Struct(int[] A) { SumPair[] sumByIndex = new SumPair[A.Count()]; int thisSum = 0; int minSum = int.MaxValue; for (int i = 0; i < A.Count(); i++) { thisSum = thisSum + A[i]; if (thisSum > 0) { minSum = Math.Min(minSum, thisSum); } var sumPair = new SumPair(); sumPair.Sum = thisSum; sumPair.Index = i; sumByIndex[i] = sumPair; } Array.Sort(sumByIndex); for (int i = 1; i < sumByIndex.Count(); i++) { if (sumByIndex[i].Index > sumByIndex[i - 1].Index && (sumByIndex[i].Sum - sumByIndex[i - 1].Sum) > 0) { minSum = Math.Min(minSum, sumByIndex[i].Sum - sumByIndex[i - 1].Sum); } } return(minSum); }
static int GetMinPlusSum_nlogn_List(int[] A) { var sumByIndex = new List <SumPair>(A.Count()); int thisSum = 0; int minSum = int.MaxValue; for (int i = 0; i < A.Count(); i++) { thisSum = thisSum + A[i]; if (thisSum > 0) { minSum = Math.Min(minSum, thisSum); } var sumPair = new SumPair(); sumPair.Sum = thisSum; sumPair.Index = i; sumByIndex.Add(sumPair); } sumByIndex.Sort(); for (int i = 1; i < sumByIndex.Count(); i++) { if (sumByIndex[i].Index > sumByIndex[i - 1].Index && (sumByIndex[i].Sum - sumByIndex[i - 1].Sum) > 0) { minSum = Math.Min(minSum, sumByIndex[i].Sum - sumByIndex[i - 1].Sum); } } return(minSum); }