Two-pointer technique
来源:互联网 发布:淘宝买家好评率百分百 编辑:程序博客网 时间:2024/06/07 01:22
https://leetcode.com/articles/two-pointer-technique/
I. Two-pointer technique:
One slow-runner and the other fast-runner.One pointer starts from the beginning while the other pointer starts from the end.
e.g. Reverse the characters in a string:
First, let's assume that we already have the swap
function defined below:
private void swap(char[] str, int i, int j) { char temp = str[i]; str[i] = str[j]; str[j] = temp;}
The idea is to swap the first character with the end, advance to the next character and swapping repeatedly until it reaches the middle position. We calculate the middle position as ⌊2n⌋. You should verify that the middle position works for both odd and even size of array.
public void reverse(char[] str) { int n = str.length; for (int i = 0; i < n / 2; i++) { swap(str, i, n - i - 1); }}
Or we can also solve the problem using the two-pointer technique.
public void reverse(char[] str) { int i = 0, j = str.length - 1; while (i < j) { swap(str, i, j); i++; j--; }}
Classic problems:
- Remove Duplicates from Sorted Array
- Two Sum II - Input array is sorted
- Reverse Words in a String II
- Rotate Array
- Valid Palindrome
- Container With Most Water
- Product of Array Except Self
0 0
- Two-pointer technique
- [Algorithm]九章七:Two Pointer
- 11572 - Unique Snowflakes(two pointer)
- 掉坑记录--two pointer
- 【two-pointer】Codeforces762C[Two strings]题解
- The two-dimensional pointer operation in C++
- 11536 - Smallest Sub-Array (two pointer)
- CF-395A1 Skis (two pointer)
- String two pointer swapping (合集)
- LeetCode Minimum Window Substring(two pointer)
- [POJ 2100] Graveyard Design (Two Pointer)
- LeetCode 16. 3Sum Closest (Two-Pointer)
- Copy List with Random Pointer(two pointers)
- [two-pointer ST表] HDU5289: Assignment
- Copy List with Random Pointer & Add Two Numbers & Valid Palindrome
- 076.Pointer Two Array 指向多维数组的指针
- 076.Pointer Two Array 指向多维数组的指针
- div.2/C. They Are Everywhere<two pointer>
- 函数返回值与不同存储位置字符串的“坑”
- Android 日常碎片知识总结之布局中的小技巧
- zmodem transfer canceled by remote side问题解决
- linux之od命令总结
- oracle v$视图
- Two-pointer technique
- C#高效开发的小技巧——为常用语句添加代码段
- idea如何查看jar包的源代码(非反编译)
- junit单元测试的Test注解
- 关于 iw
- Hibernate属性级别注解
- oracle数据库操作系统CPU利用率居高不下
- SwipeRefreshLayout下拉刷新跟listview下拉滑动冲突解决
- Flask 路由 route