-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFirstAndLastIndices.java
49 lines (39 loc) · 1.07 KB
/
FirstAndLastIndices.java
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
package com.leetcode.algorithms.medium.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
public class FirstAndLastIndices {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int target = scanner.nextInt();
String[] inputs = InputUtil.inputArr(input);
int[] nums = InputUtil.integerArr(inputs);
// Print output
System.out.println(Arrays.toString(getRange(nums, target)));
scanner.close();
}
static int[] getRange(int[] nums, int target) {
int[] result = new int[2];
List<Integer> index = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
index.add(i);
}
}
if (index.size() > 1) {
result[0] = index.get(0);
result[1] = index.get(index.size() - 1);
} else if (index.size() == 1) {
result[0] = index.get(0);
result[1] = index.get(0);
} else {
result[0] = -1;
result[1] = -1;
}
return result;
}
}