• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

LeetCode Easy: 27. Remove Element

一、题目

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 by modifying the input array in-place with O(1) extra memory.

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

不借助新的空间,删除给定数组中的与给定的 val 相同的元素,返回新数组的长度,新数组的末尾是什么不关心。

二、思路

首先不考虑鲁棒性,定义两个指针,其中一个指针遍历整个数组,另外一个指针负责计数即当前数组元素不等于给定 val 时做加 1操作 ,同时将该元素前移。大的考虑就这些。

三、代码

#coding:utf-8
def removeElement(nums, val):
    """
    :type nums: List[int]
    :type val: int
    :rtype: int
    """
    numslenth = len(nums)
    j=0
    # if numslenth == 0:
    #     return 0
    # if numslenth == 1 and val == nums[0] :
    #     return 0
    # if numslenth == 1 and val != nums[0] :
    #     return 1
    for i in range(0,numslenth):
        if nums[i] != val:
            nums[j] = nums[i]
            j += 1
    print(j,"\n",nums)
    return j
if __name__ == '__main__':
    nums = [5]
    val = 3
    removeElement(nums,val)

  

 

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-03-23 09:08  乐晓东随笔  阅读(127)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3