递归删除数组中所有相邻的重复数字

时间:2019-03-23 22:12:32

标签: java arrays algorithm recursion

我想递归地删除数组中所有相邻的重复数字

我已经通过类似的链接在字符串上进行了

https://www.geeksforgeeks.org/recursively-remove-adjacent-duplicates-given-string/

以下是用于删除字符串中相邻重复项的代码,我想知道是否存在一种理想的方式来处理相同的行,但可以在数组上运行

  static String removeUtil(String str, char last_removed) 
  { 
         // If length of string is 1 or 0  
         if (str.length() == 0 || str.length() == 1) 
             return str; 

         // Remove leftmost same characters and recur for remaining   
         // string  
         if (str.charAt(0) == str.charAt(1)) 
         { 
             last_removed = str.charAt(0); 
             while (str.length() > 1 && str.charAt(0) == str.charAt(1)) 
                   str = str.substring(1, str.length()); 
             str = str.substring(1, str.length()); 
             return removeUtil(str, last_removed);  
         } 

         // At this point, the first character is definiotely different   
         // from its adjacent. Ignore first character and recursively   
         // remove characters from remaining string  
         String rem_str = removeUtil(str.substring(1,str.length()), last_removed); 

         // Check if the first character of the rem_string matches with   
         // the first character of the original string 
         if (rem_str.length() != 0 && rem_str.charAt(0) == str.charAt(0)) 
         { 
            last_removed = str.charAt(0); 
            return rem_str.substring(1,rem_str.length()); // Remove first character 
         }  


         // If remaining string becomes empty and last removed character  
         // is same as first character of original string. This is needed  
         // for a string like "acbbcddc"  
         if (rem_str.length() == 0 && last_removed == str.charAt(0)) 
             return rem_str; 

         // If the two first characters of str and rem_str don't match,   
         // append first character of str before the first character of  
         // rem_str 
         return (str.charAt(0) + rem_str); 
  } 

假设输入数组为

1)[2,3,3]-输出为[2]

2)[1,2,3,3,2]-[1,2,2]-输出为[1]

3)[2,0,0,2,3,3,0,0,1,1]-输出为[]

编辑-如果有人还在寻找解决方案,我想出了一条出路。我修复了@kemalturgul解决方案中的错误。这对我有用。

public static int[] removeUtil(int[] arr) 
{
    int i=0;
    boolean check = false;

    for (i = 0; i < arr.length - 1; i++) 
    {
        if (arr[i] == arr[i + 1]) 
        {
            check = true;
            break;
        }
    }

    if(check)
        return removeUtil(combineTwoArray(Arrays.copyOfRange(arr, 0, i), Arrays.copyOfRange(arr, i + 2, arr.length)));
    else
        return arr;

}

public static int[] combineTwoArray(int[] arr1, int[] arr2) {
    int[] newArr = Arrays.copyOf(arr1, arr1.length + arr2.length);
    for (int j = 0; j < arr2.length; j++) 
        newArr[arr1.length + j] = arr2[j];

    return newArr;
}

5 个答案:

答案 0 :(得分:1)

您只需使用ArrayDeque即可完成操作。

只需将数组中的每个数字都放在堆栈上,在每次堆栈顶部的每次迭代中检查重复的数字,如果找到,则将其删除。

答案 1 :(得分:0)

是的,您可以接受int[]而不是String的直接翻译。

我认为str.length()str.charAt(index)的翻译是微不足道的。

对于str.substring(1, str.length(),您需要Arrays.copyOfRange(arr, 1, arr.length)(自Java 1.6开始)。

顺便说一句,可能不仅有一种“删除相邻重复项”的有效方法。例如:

  • [3,1,2,2,1,3,3]→[3,1,1,3,3]→[3,1,1]→[3]
  • [3,1,2,2,1,3,3]→[3,1,1,3,3]→[3,3,3]→[]

另一个例子:

  • [1、2、2、1、2、2、1]→[1、2、2、2、1]→[1、1、1]→[]
  • [1、2、2、1、2、2、1]→[1、2、2、2、1]→[2、2、1]→[1]

答案 2 :(得分:0)

这是递归解决方案:

    public static int[] removeUtil(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] == arr[i + 1]) {
                System.out.println(Arrays.toString(arr));
                return removeUtil(combineTwoArray(Arrays.copyOfRange(arr, 0, i), Arrays.copyOfRange(arr, i + 2, arr.length)));
            }
        }
        return arr;

    }

    public static int[] combineTwoArray(int[] arr1, int[] arr2) {
        int[] newArr = Arrays.copyOf(arr1, arr1.length + arr2.length);
        for (int j = 0; j < arr2.length; j++) {
            newArr[arr1.length + j] = arr2[j];
        }
        return newArr;
    }

答案 3 :(得分:0)

    public class Main {

        public static void main(String[] args) {
            System.out.println(Arrays.toString(removeDuplicates(new int[] {2, 0, 0, 2, 3, 3, 0, 0, 1, 1})));
        }

         public static int[] removeDuplicates(int[] arr) {
             int[] stack = new int[arr.length];

             int i = 0;

             for(int j = 0 ; j < arr.length ; j++) {

                 int currentNumber = arr[j];
                 if(i > 0 && stack[i-1] == currentNumber) {
                     i--;
                 }else {
                     stack[i] = currentNumber;
                     i++;
                 }

             }
             return Arrays.copyOfRange(stack , 0 , i);
         }

    }

该程序的结果是:

   Input is [2,3,3] - output is [2]

   input is [1,2,3,3,2] - output is [1]

   input is [2, 0, 0, 2, 3, 3, 0, 0, 1, 1] - output is []

答案 4 :(得分:-1)

不使用递归的替代解决方案。 并且使用列表而不是字符串,这应该避免任何转换错误(int <-> String)。

 static int [] remover(int [] str){
        //List to hold result
        List<Integer> l = new ArrayList();
        for(int i=0; i<str.length-1; i++){
            if(str[i]!=str[i+1])
                l.add(str[i]);   //keep adjacent distinct value
        }
        l.add(str[str.length-1]);   //add last value
        //convert list to array back
        return l.stream().mapToInt(Integer::intValue).toArray();
    }