給定數組,包含正負整數,找出對應和值最大的子數組;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