# A. Find Target Indices After Sorting Array (opens new window)
Sort
DETAILS
vector<int> targetIndices(vector<int>& A, int target) {
sort(A.begin(), A.end());
vector<int> ans;
for (int i = 0; i < A.size(); ++i)
if (A[i] == target)
ans.push_back(i);
return ans;
}
DETAILS
def targetIndices(self, A: List[int], target: int) -> List[int]:
A.sort()
ans = []
for i, x in enumerate(A):
if x == target:
ans.append(i)
return ans
# B. K Radius Subarray Averages (opens new window)
Prefix sum.
DETAILS
def getAverages(self, A: List[int], k: int) -> List[int]:
res = [0] + list(itertools.accumulate(A))
ans, n = [-1] * len(A), len(A)
if n <= 2 * k:
return ans
for i in range(k, n - k):
ans[i] = (res[i + k + 1] - res[i - k]) // (2 * k + 1)
return ans
# C. Removing Minimum and Maximum From Array (opens new window)
Locate the position of minimum value and the maximum value, which seperate the array into 3 parts, remove the rest two smallest parts.
DETAILS
def minimumDeletions(self, A: List[int]) -> int:
a, b, n = min(A), max(A), len(A)
if a == b:
return 1
i, j = A.index(a), A.index(b)
if i > j:
i, j = j, i
res = max(j - i - 1, n - j - 1, i)
return n - res
# D. Find All People With Secret (opens new window)
BFS
DETAILS
def findAllPeople(self, n: int, M: List[List[int]], firstPerson: int) -> List[int]:
can = {0, firstPerson}
for _, grp in groupby(sorted(M, key=lambda x: x[2]), key=lambda x: x[2]):
queue = set()
graph = defaultdict(list)
for x, y, _ in grp:
graph[x].append(y)
graph[y].append(x)
if x in can:
queue.add(x)
if y in can:
queue.add(y)
queue = deque(queue)
while queue:
x = queue.popleft()
for y in graph[x]:
if y not in can:
can.add(y)
queue.append(y)
return can