zoukankan      html  css  js  c++  java
  • LeetCode 27. Remove Element 题解

    Total Accepted: 122406 Total Submissions: 356377 Difficulty: Easy
    Given an array and a value, remove all instances of that value in place and return the new length.

    Do not allocate extra space for another array, you must do this in place with constant memory.

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

    Example:
    Given input array nums = [3,2,2,3], val = 3

    Your function should return length = 2, with the first two elements of nums being 2.

    public class Solution {
        public int removeElement(int[] nums, int val) {
            // if (nums.length == 0) 
            //     return 0;
                
            // int i = 0, j = nums.length - 1;
        
            // while ( i <= j ){
            //     if ( nums[i] == val ){
            //         int temp = nums[i];
            //         nums[i] = nums[j];
            //         nums[j] = temp;
            //         j--;
            //     } else {
            //         i++;
            //     }
            // }
            
            // return j + 1;
            
            int newIndex = 0;  
            for (int oldIndex = 0; oldIndex < nums.length; ++oldIndex) {  
                if (nums[oldIndex] != val) {  
                    nums[newIndex] = nums[oldIndex];//可以覆盖val所占空间
                    newIndex++;
                }   
            }  
            return newIndex;  
            
        }
    }
    
  • 相关阅读:
    urlrewrite地址重写的使用
    算法学习
    数据库之Case When
    速卖通返回503错误
    概述:软件开发工具
    c#将List&lt;T&gt;转换成DataSet
    表单域规范写法
    ant打包和jar包混淆
    Node.js文档和教程
    webpack开发和生产两个环境的配置详解
  • 原文地址:https://www.cnblogs.com/liveandlearn/p/5583361.html
Copyright © 2011-2022 走看看