Input: groups =[8,4,3,2,4], elements =[4,2]Output: [0,0,-1,1,0]Explanation:
*`elements[0] = 4`is assigned to groups 0,1, and 4.*`elements[1] = 2`is assigned to group 3.* Group 2 cannot be assigned any element.
Input: groups =[2,3,5,7], elements =[5,3,3]Output: [-1,1,0,-1]Explanation:
*`elements[1] = 3`is assigned to group 1.*`elements[0] = 5`is assigned to group 2.* Groups 0 and 3 cannot be assigned any element.
Input: groups =[10,21,30,41], elements =[2,1]Output: [0,1,0,1]Explanation:
`elements[0] = 2`is assigned to the groups with even values, and `elements[1] = 1`is assigned to the groups with odd values.
For each group, we want to find the first element (smallest index) that divides the group size. If no such element exists, we assign -1. This can be done by checking each element for each group.
classSolution {
publicint[]assignElements(int[] groups, int[] elements) {
int[] ans =newint[groups.length];
for (int i = 0; i < groups.length; i++) {
ans[i]=-1;
for (int j = 0; j < elements.length; j++) {
if (groups[i]% elements[j]== 0) {
ans[i]= j;
break;
}
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funassignElements(groups: IntArray, elements: IntArray): IntArray {
val ans = IntArray(groups.size) { -1 }
for (i in groups.indices) {
for (j in elements.indices) {
if (groups[i] % elements[j] ==0) {
ans[i] = j
break }
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
from typing import List
classSolution:
defassignElements(self, groups: List[int], elements: List[int]) -> List[int]:
ans: list[int] = [-1] * len(groups)
for i, g in enumerate(groups):
for j, e in enumerate(elements):
if g % e ==0:
ans[i] = j
breakreturn ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnassign_elements(groups: Vec<i32>, elements: Vec<i32>) -> Vec<i32> {
letmut ans =vec![-1; groups.len()];
for (i, &g) in groups.iter().enumerate() {
for (j, &e) in elements.iter().enumerate() {
if g % e ==0 {
ans[i] = j asi32;
break;
}
}
}
ans
}
}