Created
June 3, 2018 22:04
-
-
Save jsbonso/316dc97cea4571acd7fd2f5cf3c61ee5 to your computer and use it in GitHub Desktop.
Get 1st and Last Occurence of an element in an Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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