Как сжать массив так, чтобы не появилось два последовательных или более последовательных значения, и заменить это одно значение - PullRequest
1 голос
/ 14 января 2020
 /**
     * squeeze() takes an array of ints. On completion the array contains the
     * same numbers, but wherever the array had two or more consecutive
     * duplicate numbers, they are replaced by one copy of the number. Hence,
     * after squeeze() is done, no two consecutive numbers in the array are the
     * same.
     * 
     * Any unused elements at the end of the array are set to -1.
     * 
     * For example, if the input array is [ 4 , 1 , 1 , 3 , 3 , 3 , 1 , 1 ], it
     * reads [ 4 , 1 , 3 , 1 , -1 , -1 , -1 , -1 ] after squeeze() completes.
     * @param ints
     *            the input array.
     */
    public static void squeeze(int[] ints) {
         // TODO: Fill in your solution here. Ours takes linear time and is less than 10 lines long,
        // not counting blank/comment lines or lines already present in this file.
       // ArrayList<Integer> k = new ArrayList<Integer>();

ниже - мой код, но по какой-то причине лог c неверен, он возвращает тот же массив, переданный в функцию, а не измененный, я считаю, что большинство лог c верны если нет ошибки в операторе продолжения. Каждый раз, когда в массиве появляется один и тот же последовательный индекс, его следует заменить этим одним индексом

        int deleted = 0;
        int i = 0;
            for(int j = 1; j < ints.length; j++) {  ?
                if(ints[i] == ints[j]) {
                    deleted++;
                    continue;
                }else {
                    //k.add(ints[i]);
                    i++;
                }
            }
            ints = new int[ints.length + deleted];
            for(int s = 0; s < ints.length; s++) {
                if(ints[s] == 0) {
                    ints[s] = -1;
                }
            }
    }

    /**
     * main() runs test cases on your squeeze() method. Prints summary
     * information on basic operations and halts with an error (and a stack
     * trace) if any of the tests fail.
     */

1 Ответ

0 голосов
/ 15 января 2020

continue просто переходит в конец вашего, чтобы l oop пропустить любой код. то есть начинается следующее взаимодействие. как указано в комментариях, вам нужно изменить переданный массив, поскольку в определенном методе нет возвращаемого значения. Рассмотрим следующее ....

    int deleted = 0;
    for(int j = 0; j < (ints.length-1); j++) {  
        if (ints[j] == -1) // if -1 then we've reached the end of the original list
            break; // this breaks out of the loop even if the constraint is not met

        if(ints[j] == ints[j+1]) { // if consecutive entries are equal
           // shift all values down in the list
           for (int k = j+1; k < (ints.length-1); k++){
               ints[k] = ints[k+1];
           } // end loop k

           // set the last entry in the array to -1 since we moved everything down
           ints[ints.length-1] = -1;

           //back our loop up one so that we stay where we were in case there was 
           // more than two consecutive numbers that were the same
           j--; 
        }
    } // end loop j

    // display the result
    for (int i = 0; i < ints.length; i++)
        System.out.print(ints[i] + ", " );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...