Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int[] post4(int[] nums) {
- int startPoint = nums.length - 1;
- int[] newArray;
- int amtOfElements = 0;
- int stopIndex = 0;
- for (int i = startPoint; i >= 0; i--) {
- if (nums[i] == 4) {
- stopIndex = i;
- i = 0;
- } else {
- amtOfElements++;
- }
- }
- newArray = new int[amtOfElements];
- for (int i = 0, j = stopIndex; i < amtOfElements; i++, j++) {
- newArray[i] = nums[j + 1];
- }
- return newArray;
- }
- public int[] post4(int[] arr) {
- for(int i = arr.length-1; i >= 0; --i) {
- if(arr[i] == 4) {
- return Arrays.copyOfRange(arr, i+1, arr.length);
- }
- }
- return new int[0]; // or null
- }
- public static int[] post4(int[] nums) {
- int marker = 4;
- return IntStream.range(0, nums.length) //iterate over the indexes to find the marker
- .map(i -> nums.length - i - 1) //reverse the order to start from the back
- .filter(i -> marker == nums[i]) //find the marker
- .mapToObj(skip -> IntStream.of(nums).skip(skip+1).toArray()) //skip the first elements and the marker (+1)
- .findFirst() //the new array
- .orElse(nums); //the original array if there is no marker, or int[0] - its not that clear from your question
- }
- public int[] post4(int[] nums) {
- Stack<Integer> stack = new Stack<>();
- int i = nums.length - 1;
- while (nums[i] != 4) {
- stack.add(nums[i--]);
- }
- int[] newArray = new int[stack.size()];
- int j = 0;
- while (!stack.isEmpty()) {
- newArray[j++] = stack.pop();
- }
- return newArray;
- }
Add Comment
Please, Sign In to add comment