1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| public class 查找大小为M的最新分组_5497 {
int[] parent; int[] nums;
public int findLatestStep(int[] arr, int m) { int result = -1; int length = arr.length; int count = 0; parent = new int[length + 2]; nums = new int[length + 2]; for (int i = 1; i <= length; i++) { int index = arr[i - 1]; if (parent[index - 1] == 0 && parent[index + 1] == 0) { parent[index] = index; nums[index] = 1; if (nums[index] == m) { count++; } } else if (parent[index - 1] != 0 && parent[index + 1] == 0) { parent[index - 1] = index; parent[index] = index; nums[index] = 1 + nums[index - 1]; if (nums[index - 1] == m) { count--; } if (nums[index] == m) { count++; } } else if (parent[index - 1] == 0 && parent[index + 1] != 0) { int parentNode = findParent(index + 1); parent[index] = parentNode; if (nums[parentNode] == m) { count--; } nums[parentNode] = 1 + nums[parentNode]; if (nums[parentNode] == m) { count++; } } else { int parentNode = findParent(index + 1); parent[index] = parentNode; parent[index - 1] = parentNode; if (nums[parentNode] == m) { count--; } if (nums[index - 1] == m) { count--; } nums[parentNode] = 1 + nums[parentNode] + nums[index - 1]; if (nums[parentNode] == m) { count++; } }
if (count != 0) { result = i; } } return result; }
private int findParent(int index) { if (parent[index] != index) { return findParent(parent[index]); } return index; }
|