首页 > 其他分享 >LeetCode刷题记录.Day2

LeetCode刷题记录.Day2

时间:2022-10-31 23:44:38浏览次数:85  
标签:size nums int Day2 fastIndex vector 刷题 LeetCode 指针

移除元素

题目链接 27. 移除元素 - 力扣(LeetCode)

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int slotIndex = 0;
        for(int fastIndex = 0; fastIndex < nums.size(); fastIndex++){
            if(nums[fastIndex] != val){
                nums[slotIndex++] = nums[fastIndex];
            }
        }
        return slotIndex;
    }
};

学习了一下双指针法解题。双指针法倒是因为快速排序会用到知道一点。跟着刷题也系统性的接触了一下。重点学习了快慢指针 "一个循环完成两层循环的工作"的思想。

有序数组的平方

题目链接 代码随想录 (programmercarl.com)

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int index = nums.size() - 1;
        vector<int> result(nums.size(), 0);
        for(int l = 0, r = nums.size() - 1;l <= r;){
            if (nums[l] * nums[l] < nums[r] * nums[r]){
                result[index--] = nums[r] * nums[r];
                r--;
            }
            else{
                result[index--] = nums[l] * nums[l];
                l++;
            }
        }
        return result;
    }
};

同样使用双指针法,不过这次是左右指针。因为根据题目特性可能出现负数的平方数大于该位置的正整数的情况。但是因为平方运算之前是顺序排列,所以可以使用双指针法,比较大小后更新左或者右指针位置。因为如果右指针的这一位比左指针的大,那么肯定比左指针靠右的所有数据要大,所以此时新的数组数据为右指针指向的数据,同时右指针左移,反之一样。总的来说还算好理解。

标签:size,nums,int,Day2,fastIndex,vector,刷题,LeetCode,指针
From: https://www.cnblogs.com/tianmaster/p/16846346.html

相关文章

  • [Leetcode Weekly Contest]317
    链接:LeetCode[Leetcode]2455.可被三整除的偶数的平均值给你一个由正整数组成的整数数组nums,返回其中可被3整除的所有偶数的平均值。注意:n个元素的平均值等于n个......
  • Leetcode第481题:神奇字符串(Magical string)
    解题思路根据题意,我们可以把ss看成是由「11组」和「22组」交替组成的,重点在于每组内的数字是一个还是两个,这可以从ss自身上知道。构造到ss的长度达到nn时停止......
  • leetcode-191-easy
    NumberOf1BitsWriteafunctionthattakesanunsignedintegerandreturnsthenumberof'1'bitsithas(alsoknownastheHammingweight).Note:Notetha......
  • leetcode-278-easy
    FirstBadVersionYouareaproductmanagerandcurrentlyleadingateamtodevelopanewproduct.Unfortunately,thelatestversionofyourproductfailsthe......
  • leetcode-268-easy
    MissingNumberGivenanarraynumscontainingndistinctnumbersintherange[0,n],returntheonlynumberintherangethatismissingfromthearray.Exam......
  • leetcode-500-easy
    KeyboardRowGivenanarrayofstringswords,returnthewordsthatcanbetypedusinglettersofthealphabetononlyonerowofAmericankeyboardliketheim......
  • leetcode-1356-easy
    SortIntegersbyTheNumberOf1BitsYouaregivenanintegerarrayarr.Sorttheintegersinthearrayinascendingorderbythenumberof1'sintheirbinar......
  • day22 ajax
    概述:AJAX(asynchronousJavaScriptandxml)异步的Javascript和xml。用于发送http请求(可以是异步请求),能够完成页面的局部刷新功能,在整个页面不刷新的前提下,发送对应的请求......
  • 刷题 二叉树
    代码随想录LeetCode110. 平衡二叉树carl递归思路方法一:递归求高度、递归判断是否平衡方法二:递归求高度过程中判断是否平衡细节略LeetCode257. 二叉树的......
  • leetcode-1-easy
    TwoSumGivenanarrayofintegersnumsandanintegertarget,returnindicesofthetwonumberssuchthattheyadduptotarget.Youmayassumethateachinp......