zoukankan      html  css  js  c++  java
  • Remove Element

    问题描述

    Given an array and a value, remove all instances of that value in place and return the new length.

    The order of elements can be changed. It doesn't matter what you leave beyond the new length. 

    解决思路

    双指针,起始状态两个指针p和q指向首元素,指针p指向的位置表示在此之前的元素均为正常元素(不被移除的)。

    如果p指向的元素为正常元素,则p和q均向前一步;否则,找到第一个q指向的正常元素作交换。

    注意控制边界条件,防止指针越界。

    程序

    public class Solution {
        public int removeElement(int[] nums, int val) {
            if (nums == null || nums.length == 0) {
                return 0;
            }
            int len = nums.length;
            int p = 0, q = 0;
            while (p < len && q < len) {
                if (nums[p] != val) {
                    ++p;
                    ++q;
                    continue;
                }
                while (q < len && nums[q] == val) {
                    ++q;
                }
                if (q == len) {
                    break;
                }
                // swap q and p
                int tmp = nums[p];
                nums[p] = nums[q];
                nums[q] = tmp;
            }
            return p;
        }
    }
    

      

  • 相关阅读:
    WebView loadData乱码问题
    记录常用工具
    android toolbar学习
    百度地图V5.0地图定位
    JS调JAVA代码
    开始使用Android Stdio
    记录下平时看到的好句子
    开发者必备网址
    android:ellipsize实现跑马灯效果总结
    seo查询命令
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4672342.html
Copyright © 2011-2022 走看看