用ArrayList存数后,怎么让集合里的数求和
1、先将两数组排序,然后两数组先分别求和;
3、然后将和大的数组中值最接近b的数与和小的数组中最小值交换。多次执行这个过程,直到绝对值最小为止。
例:
(1)public static void AverageArray();
(2){;
(3)int[] values = {1, 300, 20, 11, 5, 301};
(4)int n = values.Length / 2;
(5)int halfSum = values.Sum() / 2;
(6)List<List<List<int>>> heap = new List<List<List<int>>>(n + 1);
(7)heap.Add(new List<List<int>>());
(8)heap[0].Add(new List<int>());
(9)heap[0][0].Add(0);
(10)#region Seek the array;
(11)for (int k = 1; k <= 2 * n; k++);
(12){;
(13)int i = 1;
(14)if (k <= n);
(15){;
(16)i = k;
(17)heap.Add(new List<List<int>>());
(18)};
(19)else;
(20){;
(21)i = n;
(22)};
(23)for (; i >= 1; i--);
(24){;
(25)foreach (List<int> tempList in heap[i - 1]);
(26){;
(27)if(tempList[0] + values[k - 1] <= halfSum);
(28){;
(29)List<int> newList = new List<int>(tempList);
(30)newList[0] += values[k - 1];
(31)newList.Add(k - 1);
(32)heap[i].Add(newList);
(33)};
(34)};
(35)};
(36)};
(37)#endregion;
(38)List<List<int>> result = heap[n];
(39)for (int k = 0; k + 1 < result.Count; );
(40){;
(41)if (result[k][0] > result[k + 1][0]);
(42){;
(43)result.RemoveAt(k + 1);
(44)};
(45)else if (result[k][0] == result[k + 1][0]);
(46){;
(47)k++;
(48)};
(49)else;
(50){;
(51)result.RemoveRange(0, k + 1);
(52)k = 0;
(53)};
(54)};
(55)}。
2017-08-20 · 知道合伙人互联网行家
List list=new ArrayList();
list.add(1);
list.add(3);
list.add(5);
int sum=0;
for(int i=0;i<list.size();i++){
int j=(Integer) list.get(i);
sum+=j;
}
List list=new ArrayList();
list.add(1);
list.add(3);
list.add(5);
int sum=0;
for(int i=0;i<list.size();i++){
int j=(Integer) list.get(i);
sum+=j;
}