I don't like the same number. It's an example question.

Asked 2 years ago, Updated 2 years ago, 81 views

import java.util.*;

public class Solution { public int[] solution(int []arr) { int[] ans = new int[100]; int cur=arr[0]; int j=0; for(int i=1;i<arr.length;i++){ if(cur!=arr[i]){ ans[j]=cur; ans[j+1]=arr[i]; j++; cur=arr[i]; } } int[] answer = new int[j+1]; for(int b=0;b<answer.length;b++){ answer[b]=ans[b]; } return answer; } }

An ArrayIndexOutOfBoundsException error when running without creating an array changes the number of elements in a given array arr It floats and eventually puts a value in the answer array and creates a new answer array that has a length of that value When I put it back in and run, it says that the result is correct, but it is not efficient... I think it's inefficient because you don't put a value in the answer array I'd appreciate it if you could tell me how to do itㅠ<

algorithm java array

2022-09-22 20:15

1 Answers

If we're going to eliminate the same consecutive numbers, how about the following?

public List<Integer> solution2(int[]arr) {
    final List<Integer> answer = new ArrayList<>();
    int value = arr[0];
    answer.add(value);
    for (int i = 1; i < arr.length; i++) {
        if (value != arr[i]) {
            answer.add(arr[i]);
            value = arr[i];
        }
    }
    return answer;
}


2022-09-22 20:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.