给定数组,包含正负整数,找出对应和值最大的子数组;c++
一个数只有加上大于0的正整数才会愈来愈大,不然遇到小于0的负整数从新计数;git
int[] arr = { 3, -6, 1, 2, 3, -1, 2, -5, 1, 2 }; #region 找出最大加值子数组 static string maxSubArr(int[] arr) { int sum = 0; int start = 0; int end = 0; int temp = 0; for (int i = 0; i < arr.Length; i++) { if (temp < 0) { start = i; temp = arr[i]; } else { temp += arr[i]; } if (sum < temp) { sum = temp; end = i; } } return start + "," + end; } #endregion // start和end是子串头尾的两个坐标
1,2,3,-1数组
给定数组包含正负整数,如何将正整数放左,负整数放右。可采用插入排序;.net
static int[] arr3 = { 1, -2, -4, 5, 6, -3, -8, 6 }; static void leftOrRight2(int[] arr) { int start = 0; int end = arr.Length - 1; while (start != end) { while (start < end && arr[start] < 0) { start++; } while (start < end && arr[end] >= 0) { end--; } if (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; } } }
static int[] arr4 = { 0, 2, 2, 1, 2, 0, 2, 0 }; #region 找到数组中出现最多的元素 static void findMaxDisplay(int[] arr) { int v = arr[0]; int c = 0; for (int i = 0; i < arr.Length; i++) { if (v == arr[i]) { c++; } else { c--; } if (c == 0) { v = arr[i]; c = 1; } } System.Console.WriteLine(v); } #endregion