首页 > 其他分享 >leetcode 27. Remove Element

leetcode 27. Remove Element

时间:2023-05-30 17:33:50浏览次数:78  
标签:27 val nums int Remove length len array leetcode

Given an array nums and a value val, 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

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

Example 1:

Given nums = [3,2,2,3], val = 3,

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

It doesn't matter what you leave beyond the returned length.

Example 2:

5
nums
0
1
3
0

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        valid_pos = 0
        ans = 0
        for i in xrange(0, len(nums)):
            if nums[i] != val:
                nums[valid_pos] = nums[i]
                valid_pos += 1
                ans += 1
        return ans

 快排思路:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        start, end = 0, len(nums)-1
        while start <= end:
            if nums[start] == val:
                nums[start], nums[end] = nums[end], nums[start]
                end -= 1 
            else:
                start += 1
        return start

 

标签:27,val,nums,int,Remove,length,len,array,leetcode
From: https://blog.51cto.com/u_11908275/6381016

相关文章

  • leetcode 594. Longest Harmonious Subsequence
    Wedefineaharmoniousarrayisanarraywherethedifferencebetweenitsmaximumvalueanditsminimumvalueisexactly1.Now,givenanintegerarray,youneedtofindthelengthofitslongestharmonioussubsequenceamongallitspossiblesubsequences.E......
  • leetcode 836. Rectangle Overlap
    Arectangleis representedasa list[x1,y1,x2,y2],where (x1,y1) arethecoordinatesofitsbottom-leftcorner,and(x2, y2) arethecoordinatesofitstop-rightcorner.Tworectanglesoverlapiftheareaoftheirintersectionispositive. Tobecl......
  • leetcode 342. Power of Four
    Givenaninteger(signed32bits),writeafunctiontocheckwhetheritisapowerof4.Example:Givennum=16,returntrue.Givennum=5,returnfalse.Followup:Couldyousolveitwithoutloops/recursion?解法1,经典的数学解法:classSolution(object):def......
  • leetcode 345. Reverse Vowels of a String
    Writeafunctionthattakesastringasinputandreverseonlythevowelsofastring.Example1:Givens="hello",return"holle".Example2:Givens="leetcode",return"leotcede".Note:Thevowelsdoesnotincl......
  • leetcode Most Common Word——就是在考察自己实现split
    819.MostCommonWordGivenaparagraph andalistofbannedwords,returnthemostfrequentwordthatisnotinthelistofbannedwords. Itisguaranteedthereisatleastonewordthatisn'tbanned,andthattheanswerisunique.Wordsinthelist......
  • leetcode Kth Largest Element in a Stream——要熟悉heapq使用
    703.KthLargestElementinaStreamEasyDesignaclasstofind thekthlargestelementinastream.Notethatitisthekthlargestelementinthesortedorder,notthekthdistinctelement.Your KthLargest classwillhaveaconstructorwhichacceptsanin......
  • leetcode 2712. 使所有字符相等的最小成本
    2712.使所有字符相等的最小成本给你一个下标从 0 开始、长度为 n 的二进制字符串 s ,你可以对其执行两种操作:选中一个下标 i 并且反转从下标 0 到下标 i(包括下标 0 和下标 i )的所有字符,成本为 i+1 。选中一个下标 i 并且反转从下标 i 到下标 n-......
  • leetcode 2707. 字符串中的额外字符
    2707.字符串中的额外字符给你一个下标从 0 开始的字符串 s 和一个单词字典 dictionary 。你需要将 s 分割成若干个 互不重叠 的子字符串,每个子字符串都在 dictionary 中出现过。s 中可能会有一些 额外的字符 不在任何子字符串中。请你采取最优策略分割 s......
  • 又双叒添新证书:上海斯歌通过ISO9001和ISO27001认证
    近期,上海斯歌顺利通过权威机构审查,正式成为ISO9001质量管理体系和ISO27001信息管理安全体系双重认证企业。 可以说ISO9001及ISO27001的认证,既是斯歌坚持管理标准化、程序化、规范化的成果;也是国际标准化组织(ISO)依据我国相关产品质量标准及法规,对斯歌的产品质量、顾客满意度及信......
  • [LeetCode] 51. N-Queens
    The n-queens puzzleistheproblemofplacing n queensonan nxn chessboardsuchthatnotwoqueensattackeachother.Givenaninteger n,return alldistinctsolutionstothe n-queenspuzzle.Youmayreturntheanswerin anyorder.Eachsolution......