2017.10.20 LeetCode Two Pointers 26. 27.
来源:互联网 发布:mysql索引失效 in or 编辑:程序博客网 时间:2024/04/27 13:51
26. Remove Duplicates from Sorted Array
Description
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
题意: 给你一个数组,让你返回不同元素的个数 cnt,并且保证数组的前cnt个都是不同的
分析: 本题呢算是一种裸的Two Pointers 吧就是枚举两个端点,如果出现相同的话,就录下,不同的话就让当前的值移动到 (i-cnt)这来,自己模拟下就OK了
参考函数
class Solution {public: int removeDuplicates(vector<int>& nums) { int ans = 0; for(int i = 1;i < nums.size();i++) { if(nums[i] != nums[i-1]) { nums[i-ans] = nums[i]; }else { ans++; } } return nums.size() - ans; }};
27. Remove Element
Description
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.
题意: 将数组里的所有val值去掉,返回长度假设为len,那么前len个值都不等于val
分析: 和上一个题类似直接枚举即可
参考函数
class Solution {public: int removeElement(vector<int>& nums, int val) { int cnt = 0; int len = nums.size(); for(int i = 0;i < len;i++) { if(nums[i] == val) { cnt++; } else { nums[i - cnt] = nums[i]; } } return len - cnt; }};
- 2017.10.20 LeetCode Two Pointers 26. 27.
- LeetCode--Two Pointers
- Leetcode - Pointers/Array - Two sum
- [leetcode][two pointers] 3Sum
- [leetcode][two pointers] Remove Element
- [leetcode][two pointers] Sort Colors
- LeetCode 之双指针 two pointers
- [leetcode][two pointers] Container With Most Water
- [leetcode][two pointers][大数] 3Sum Closest
- [leetcode][two pointers] Trapping Rain Water
- [leetcode][array][two pointers] Merge Sorted Array
- [leetcode][string][two pointers] Valid Palindrome
- [leetcode][list][two pointers] Linked List Cycle
- [leetcode][two pointers] Minimum Size Subarray Sum
- leetcode -- Sort Colors -- 重点,排序,two pointers
- LeetCode *** 15. 3Sum (Two Pointers )
- LeetCode *** 18. 4Sum (Two Pointers)
- LeetCode:LinkedList,Two Pointers,Binary Search
- linux使用php动态安装模块mysqli.so(ext/mysqlnd/mysqlnd.h: 没有那个文件或目录)
- 数据结构与算法(Java描述)-5、循环链表仿真链表以及循环链表应用
- 【20171020】常用经典算法介绍
- PullToRefresh ScrollView的Listview和轮播图布局
- 博客搬迁
- 2017.10.20 LeetCode Two Pointers 26. 27.
- 快速排序
- 给定填充0和1的二维二进制矩阵,找到包含所有的最大矩形并返回其区域。
- mysql授权表
- sql内链接,左连接,右链接和多表笛卡儿积
- PullToRefresh ScrollView的Listview和轮播图Fragment布局
- python高阶函数调用
- 写什么随机化!(非酋的怒吼)
- 新环境编译安装CentOS 7 php7