Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save jsbonso/316dc97cea4571acd7fd2f5cf3c61ee5 to your computer and use it in GitHub Desktop.

Select an option

Save jsbonso/316dc97cea4571acd7fd2f5cf3c61ee5 to your computer and use it in GitHub Desktop.
Get 1st and Last Occurence of an element in an Array
String nums = "1 2 3 3 3 3 4 5 6 7 8 9 10";
int target = 3;
String[] numsArray = nums.split(" ");
int firstIndex = 0;
int lastIndex = 0;
boolean firstIndexDone = false;
for (int i=0; i < numsArray.length ;i++) {
if (!firstIndexDone && Integer.parseInt(numsArray[i]) == target) {
firstIndex = i;
firstIndexDone = true;
}
if (firstIndexDone && Integer.parseInt(numsArray[i]) == target ) {
lastIndex = i;
}
}
System.out.println("firstIndex: " + firstIndex);
System.out.print("lastIndex: " + lastIndex);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment