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;
        }
    }
    

      

  • 相关阅读:
    Django中的分页操作、form校验工具
    Django之form表单操作
    手写版本orm
    mysql注入问题
    MySQL基本操作
    初识数据库
    进程池、线程池
    信号量
    event事件
    死锁
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4672342.html
Copyright © 2011-2022 走看看