zoukankan      html  css  js  c++  java
  • [Algo] 118. Array Deduplication IV

    Given an unsorted integer array, remove adjacent duplicate elements repeatedly, from left to right. For each group of elements with the same value do not keep any of them.

    Do this in-place, using the left side of the original array. Return the array after deduplication.

    Assumptions

    • The given array is not null

    Examples

    {1, 2, 3, 3, 3, 2, 2} → {1, 2, 2, 2} → {1}, return {1}

    Soltuion 1:

    public class Solution {
      public int[] dedup(int[] array) {
        // Write your solution here
        LinkedList<Integer> stack = new LinkedList<>();
        int i = 0;
        while (i < array.length) {
          int cur = array[i];
          if (!stack.isEmpty() && stack.peekFirst() == cur) {
            while (i < array.length && array[i] == cur) {
              i += 1;
            }
            stack.pollFirst();
          } else {
            stack.offerFirst(cur);
            i += 1;
          }
        }
        int[] res = new int[stack.size()];
        for (int j = res.length - 1; j >= 0; j--) {
          res[j] = stack.pollFirst();
        }
        return res;
      }
    }

    Soltuion 2:

    public class Solution {
      public int[] dedup(int[] array) {
        // Write your solution here
        // incldue end result
        int end = -1;
        for (int i = 0; i < array.length; i++) {
          int cur = array[i];
          if (end == -1 || cur != array[end]) {
            array[++end] = array[i];
          } else {
            while (i + 1 < array.length && array[i + 1] == cur) {
              i += 1;
            }
            end -= 1;
          }
        }
        return Arrays.copyOf(array, end + 1);
      }
    }
  • 相关阅读:
    顶级Kagglers的心得和技巧
    大数加法
    TensorFlow 2.0高效开发指南
    Java 8 特性 —— Stream
    Java 8 特性 —— 函数式接口
    Java 8 特性 —— 方法引用
    Java 8 特性 —— 默认方法和静态方法
    Java 8 特性 —— lambda 表达式
    Effective Java 读书笔记
    jQuery动态添加、删除按钮及input输入框
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12355423.html
Copyright © 2011-2022 走看看