双指针 — 20180928 - 20181012

同向双指针:

100. Remove Duplicates from Sorted Array

1  public  class Solution {
 2      /*
3       * @param nums: An ineger array
 4       * @return: An integer
 5       */
6      public  int removeDuplicates( int [] nums) {
 7          // write your code here
8
9          if (nums == null ||nums.length ==0 ){
 10              return 0 ;
 11          }
 12
13          int index=0 ;
 14          for ( int i=0; i<nums.length;i++){
 15              if (i==0 || nums[i]!=nums[i-1 ]){
 16                  nums[index]= nums[i];
 17                  index++ ;
 18              }
 19          }
 20
21          return index;
 22      }
 23 }

539. Move Zeroes

 1 public class Solution {
 2     /**
 3      * @param nums: an integer array
 4      * @return: nothing
 5      */
 6     public void moveZeroes(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length == 0) {
 9             return;
10         }
11
12         int zeroIndex = 0;
13         int numIndex = 0;
14         while (zeroIndex < nums.length) {
15             if (nums[zeroIndex] != 0) {
16                 swap(nums, zeroIndex, numIndex);
17                 numIndex++;
18             }
19             zeroIndex++;
20         }
21     }
22
23     public void swap(int[] num, int left, int right) {
24         int temp = num[left];
25         num[left] = num[right];
26         num[right] = temp;
 27      }
 28 }

604. Window Sum

 1 public class Solution {
 2     /**
 3      * @param nums: a list of integers.
 4      * @param k:    length of window.
 5      * @return: the sum of the element inside the window at each moving.
 6      */
 7     public int[] winSum(int[] nums, int k) {
 8         // write your code here
 9         if (nums == null || nums.length == 0 || k > nums.length) {
10             return new int[0];
11         }
12
13         int len = nums.length - k + 1;
14         int[] res = new int[len];
15
16         for (int i = 0; i < k; i++) {
17             res[0] += nums[i];
18         }
19
20         for (int j = 1; j < res.length; j++) {
21             res[j] = res[j - 1] - nums[j - 1] + nums[j + k - 1];
22         }
23         return res;
24     }
25 }

相向双指针:

415. Valid Palindrome

 1 public class Solution {
 2     /**
 3      * @param s: A string
 4      * @return: Whether the string is a valid palindrome
 5      */
 6     public boolean isPalindrome(String s) {
 7         // write your code here
 8         if (s == null || s.length() == 0) {
 9             return true;
10         }
11
12         int start = 0;
13         int end = s.length() - 1;
14         while (start < end) {
15             while (start < end && !isCharacter(s.charAt(start))) {
16                 start++;
17             }
18
19             while (start < end && !isCharacter(s.charAt(end))) {
20                 end--;
21             }
22
23             if (Character.toLowerCase(s.charAt(start)) != Character.toLowerCase(s.charAt(end))) {
24                 return false;
25             }
26             start++;
27             end--;
28         }
29         return true;
30     }
31
32     public boolean isCharacter(char c) {
33         return Character.isLetter(c) || Character.isDigit(c);
34     }
35 }

8. Rotate String

三步翻转

 1 public class Solution {
 2     /**
 3      * @param str:    An array of char
 4      * @param offset: An integer
 5      * @return: nothing
 6      */
 7     public void rotateString(char[] str, int offset) {
 8         // write your code here
 9         if (str == null || str.length == 0 || offset == 0) {
10             return;
11         }
12
13         int k = offset % str.length;
14         reverse(str, 0, str.length - k - 1);
15         reverse(str, str.length - k, str.length-1);
16         reverse(str, 0, str.length - 1);
17         return;
18     }
19
20     public void reverse(char[] str, int start, int end) {
21         while (start < end) {
22             char temp = str[start];
23             str[start] = str[end];
24             str[end] = temp;
25             start++;
26             end--;
27         }
28     }
29 }

39. Recover Rotated Sorted Array

找到翻转点,思路同上

 1 public class Solution {
 2     /**
 3      * @param nums: An integer array
 4      * @return: nothing
 5      */
 6     public void recoverRotatedSortedArray(List<Integer> nums) {
 7         // write your code here
 8         if (nums == null || nums.size() == 0) {
 9             return;
10         }
11         for (int i = 0; i < nums.size() - 1; i++) {
12             if (nums.get(i) > nums.get(i + 1)) {
13                 reverse(nums, 0, i);
14                 reverse(nums, i + 1, nums.size() - 1);
15                 reverse(nums, 0, nums.size() - 1);
16                 return;
17             }
18         }
19
20     }
21
22     public void reverse(List<Integer> nums, int start, int end) {
23         while (start < end) {
24             int temp = nums.get(start);
25             nums.set(start, nums.get(end));
26             nums.set(end, temp);
27             start++;
28             end--;
29         }
30     }
31 }

607. Two Sum III - Data structure design

 1 public class TwoSum {
 2     /**
 3      * @param number: An integer
 4      * @return: nothing
 5      */
 6     private Map<Integer, Integer> map = new HashMap<>();
 7
 8     public void add(int number) {
 9         // write your code here
10         if (map.containsKey(number)) {
11             map.put(number, map.get(number) + 1);
12             return;
13         }
14         map.put(number, 1);
15     }
16
17     /**
18      * @param value: An integer
19      * @return: Find if there exists any pair of numbers which sum is equal to the value.
20      */
21     public boolean find(int value) {
22         // write your code here
23         for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
24             if (value - entry.getKey() == entry.getKey()) {
25                 if (entry.getValue() > 1) {
26                     return true;
27                 }
28                 continue;
29             }
30             Integer targetIndex = map.get(value - entry.getKey());
31             if (targetIndex != null) {
32                 return true;
33             }
34         }
35         return false;
36     }
37 }

608. Two Sum II - Input array is sorted

 1 public class Solution {
 2     /**
 3      * @param nums:   an array of Integer
 4      * @param target: target = nums[index1] + nums[index2]
 5      * @return: [index1 + 1, index2 + 1] (index1 < index2)
 6      */
 7     public int[] twoSum(int[] nums, int target) {
 8         // write your code here
 9         int[] res = new int[2];
10         if (nums == null || nums.length == 0) {
11             return res;
12         }
13         int start = 0;
14         int end = nums.length - 1;
15         while (start < end) {
16             int sum = nums[start] + nums[end];
17             if (sum == target) {
18                 res[0] = start + 1;
19                 res[1] = end + 1;
20                 return res;
21             }
22             if (sum > target) {
23                 end--;
24             }
25             if (sum < target) {
26                 start++;
27             }
28         }
29         return res;
30     }
31 }

587. Two Sum - Unique pairs

 1 public class Solution {
 2     public int twoSum(int[] nums, int target) {
 3         // write your code here
 4         if (nums == null || nums.length == 0) {
 5             return 0;
 6         }
 7         Arrays.sort(nums);
 8         int start = 0;
 9         int end = nums.length - 1;
10         int count = 0;
11         while (start < end) {
12             int sum = nums[start] + nums[end];
13             if (sum == target) {
14                 count++;
15                 start++;
16                 end--;
17                 while (start < end && nums[start] == nums[start - 1]) start++;
18                 while (start < end && nums[end] == nums[end + 1]) end--;
19             }
20             if (sum > target) {
21                 end--;
22             }
23             if (sum < target) {
24                 start++;
25             }
26         }
27         return count;
28     }
29 }

57. 3Sum

 1 public class Solution {
 2     /**
 3      * @param numbers: Give an array numbers of n integer
 4      * @return: Find all unique triplets in the array which gives the sum of zero.
 5      */
 6     public List<List<Integer>> threeSum(int[] numbers) {
 7         // write your code here
 8         List<List<Integer>> res = new ArrayList<>();
 9         if (numbers == null || numbers.length < 3) {
10             return res;
11         }
12
13         Arrays.sort(numbers);
14         for (int i = 0; i < numbers.length - 2; i++) {
15             if (i > 0 && numbers[i] == numbers[i - 1]) continue;
16             towSum(numbers, i + 1, numbers.length - 1, 0 - numbers[i], res);
17         }
18         return res;
19     }
20
21     public void towSum(int[] numbers, int start, int end, int target, List<List<Integer>> res) {
22         while (start < end) {
23             int sum = numbers[start] + numbers[end];
24             if (sum == target) {
25                 List<Integer> pair = new ArrayList<>();
26                 pair.add(-target);
27                 pair.add(numbers[start]);
28                 pair.add(numbers[end]);
29                 res.add(pair);
30                 start++;
31                 end--;
32                 while (start < end && numbers[start] == numbers[start - 1]) start++;
33                 while (start < end && numbers[end] == numbers[end + 1]) end--;
34             }
35             if (sum > target) {
36                 end--;
37             }
38             if (sum < target) {
39                 start++;
40             }
41
42         }
43     }
44
45 }

382. Triangle Count

 1 public class Solution {
 2     /**
 3      * @param S: A list of integers
 4      * @return: An integer
 5      */
 6     public int triangleCount(int[] S) {
 7         // write your code here
 8         if (S == null || S.length < 3) {
 9             return 0;
10         }
11         Arrays.sort(S);
12         int count = 0;
13         for (int i = 2; i < S.length; i++) {
14             int left = 0;
15             int right = i - 1;
16             while (left < right) {
17                 int sum = S[left] + S[right];
18                 if (sum > S[i]) {
19                     count += right - left;
20                     right--;
21                 }
22                 if (sum <= S[i]) {
23                     left++;
24                 }
25             }
26         }
27
28         return count;
29     }
30 }

59. 3Sum Closest

 1 public class Solution {
 2     /**
 3      * @param numbers: Give an array numbers of n integer
 4      * @param target:  An integer
 5      * @return: return the sum of the three integers, the sum closest target.
 6      */
 7     public int threeSumClosest(int[] numbers, int target) {
 8         // write your code here
 9         if (numbers == null || numbers.length < 3) {
10             return 0;
11         }
12         Arrays.sort(numbers);
13         int res = numbers[0] + numbers[1] + numbers[2];
14         for (int i = 0; i < numbers.length; i++) {
15             int start = i + 1;
16             int end = numbers.length - 1;
17             int num = numbers[i];
18             while (start < end) {
19                 int sum = numbers[start] + numbers[end] + num;
20                 if (Math.abs(sum - target) < Math.abs(res - target)) {
21                     res = sum;
22                 }
23                 if (sum == target) {
24                     return target;
25                 }
26                 if (sum > target) {
27                     end--;
28                 }
29                 if (sum < target) {
30                     start++;
31                 }
32             }
33         }
34         return res;
35     }
36
37 }

31.  Partition Array(需重刷)

 1 public class Solution {
 2     /**
 3      *@param nums: The integer array you should partition
 4      *@param k: As description
 5      *return: The index after partition
 6      */
 7     public int partitionArray(int[] nums, int k) {
 8         if(nums == null || nums.length == 0){
 9             return 0;
10         }
11
12         int left = 0, right = nums.length - 1;
13         while (left <= right) {
14
15             while (left <= right && nums[left] < k) {
16                 left++;
17             }
18
19             while (left <= right && nums[right] >= k) {
20                 right--;
21             }
22
23             if (left <= right) {
24                 int temp = nums[left];
25                 nums[left] = nums[right];
26                 nums[right] = temp;
27
28                 left++;
29                 right--;
30             }
31         }
32         return left;
33     }
34 }

373. Partition Array by Odd and Even

 1 public class Solution {
 2     /*
 3      * @param nums: an array of integers
 4      * @return: nothing
 5      */
 6     public void partitionArray(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length == 0) {
 9             return;
10         }
11         int left = 0;
12         int right = nums.length - 1;
13
14         while (left <= right) {
15             while (left <= right && nums[left] % 2 == 1) {
16                 left++;
17             }
18
19             while (left <= right && nums[right] % 2 == 0) {
20                 right--;
21             }
22             if (left <= right) {
23                 int temp = nums[left];
24                 nums[left] = nums[right];
25                 nums[right] = temp;
26                 left++;
27                 right--;
28             }
29         }
30         return;
31
32     }
33 }

49. Sort Letters by Case

 1 public class Solution {
 2     /*
 3      * @param chars: The letter array you should sort by Case
 4      * @return: nothing
 5      */
 6     public void sortLetters(char[] chars) {
 7         // write your code here
 8         if (chars == null || chars.length == 0) {
 9             return;
10         }
11
12         int start = 0;
13         int end = chars.length - 1;
14         while (start <= end) {
15             while (start <= end && Character.isLowerCase(chars[start])) start++;
16             while (start <= end && !Character.isLowerCase(chars[end])) end--;
17             if (start <= end) {
18                 char temp = chars[start];
19                 chars[start] = chars[end];
20                 chars[end] = temp;
21                 start++;
22                 end--;
23             }
24         }
25         return;
26     }
27 }

148. Sort Colors

 1 public class Solution {
 2     /**
 3      * @param nums: A list of integer which is 0, 1 or 2
 4      * @return: nothing
 5      */
 6     public void sortColors(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length == 0) return;
 9
10         int left = 0;
11         int right = nums.length - 1;
12         int i = 0;
13
14         while (i <= right) {
15             if (nums[i] == 0) {
16                 int temp = nums[i];
17                 nums[i] = nums[left];
18                 nums[left] = temp;
19                 left++;
20                 i++;
21             }
22             else if (nums[i] == 1) {
23                 i++;
24             }
25             else {
26                 int temp = nums[i];
27                 nums[i] = nums[right];
28                 nums[right] = temp;
29                 right--;
30             }
31         }
32         return;
33     }
34 }

143. Sort Colors II(148的FollowUp)快排和归并排序的结合

 1 public class Solution {
 2     /**
 3      * @param colors: A list of integer
 4      * @param k:      An integer
 5      * @return: nothing
 6      */
 7     public void sortColors2(int[] colors, int k) {
 8         // write your code here
 9         if (colors == null || colors.length == 0 || k > colors.length) {
10             return;
11         }
12
13         partitionColor(colors, 0, colors.length - 1, 0, k);
14     }
15
16     //start-end 排序的数组起始下标
17     //colorFrom-colorTo 这一段的颜色
18     public void partitionColor(int[] colors, int startIndex, int endIndex, int colorFrom, int colorTo) {
19         if (colorFrom == colorTo)
20             return;
21         if (startIndex > endIndex) {
22             return;
23         }
24         int left = startIndex;
25         int right = endIndex;
26         //划分的颜色
27         int colorMid = colorFrom + (colorTo - colorFrom) / 2;
28         while (left <= right) {
29             while (left <= right && colors[left] <= colorMid) left++;
30             while (left <= right && colors[right] > colorMid) right--;
31             if (left <= right) {
32                 int temp = colors[left];
33                 colors[left] = colors[right];
34                 colors[right] = temp;
35                 left++;
36                 right--;
37             }
38         }
39         partitionColor(colors, startIndex, right, colorFrom, colorMid);
40         partitionColor(colors, left, endIndex, colorMid + 1, colorTo);
41     }
42 }

原文地址:https://www.cnblogs.com/lizzyluvcoding/p/9721031.html

时间: 2024-11-13 02:59:19

双指针 — 20180928 - 20181012的相关文章

hdu_5806_NanoApe Loves Sequence Ⅱ(双指针)

题目链接:hdu_5806_NanoApe Loves Sequence Ⅱ 题意: 给你一段数,问你有多少个区间满足第K大的数不小于m 题解: 直接双指针加一下区间就行 1 #include<cstdio> 2 #include<algorithm> 3 #define F(i,a,b) for(int i=a;i<=b;i++) 4 using namespace std; 5 typedef long long ll; 6 const int N=2e5+7; 7 in

[转]深入理解双指针(上)

转载:http://blog.csdn.net/feiyinzilgd/archive/2010/02/09/5302369.aspx  对于C语言的参数传递都是值传递,当传传递一个指针给函数的时,其实质上还是值传递,除非使用双指针. 在讲双指针之前,还是先讲讲关于C语言函数调用的本质.函 数调用操作包括从一块代码到另一块代码之间的双向数据传递和执行控制转移.数据传递通过函数参数和返回值来进行,包括局部变量的空间分配与回收,都是通过 栈来实现的.绝大多数CPU上的程序实现使用栈来支持函数调用操作

hdu 6025 card card card(双指针)

题目链接:hdu 6025 card card card 题意: 有n对数(a,b),现在你可以将前x对(a,b)移到尾部. 操作完后,现在定义sum=ai-bi (1,x),当sum<0时,当前的价值为Σai (1<=i<=x-1). 问你移动前多少对(a,b),使得价值最大,如果有多个答案,输出最小的那个. 题解: 复制一份,双指针模拟一下就行了. 1 #include<bits/stdc++.h> 2 #define F(i,a,b) for(int i=a;i<

HZAU 1205 Sequence Number(双指针)

题目链接:http://acm.hzau.edu.cn/problem.php?id=1205 [题意]给你一串数,要求你找到两个数a[i],a[j],使得a[i]<=a[j]且j>=i且j-i最大. [分析]预处理1~i的最小值,然后从右往左双指针,维护右端点>左端点,如果右端点<1~L的最小值,则移动右端点. #include <cstdio> #include <vector> #include <cstring> #include <

125. Valid Palindrome【双指针】

2017/3/15 21:47:04 Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example,"A man, a plan, a canal: Panama" is a palindrome."race a car" is not a palindrome. Note:Have y

指针 &amp;&amp; 双指针

指针是C语言中的难点,C++中自然也免不了其身影. 以下是我学习中的积累,不足之处望不吝赐教. 指针类型: 指针 Const int* pstr 不能修改被指向的对象,可以使指针指向其他对象 如:const int* pvalue {&value}; *pvalue=6; //will not compile pvalue=nullptr; //ok Int* const pstr   不能修改指针中存储的地址,可修改指向的对象 如:Int* const pvalue {&value};

百度之星2017 HDU 6119 小小粉丝度度熊 二分+双指针

小小粉丝度度熊 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6119 Description 度度熊喜欢着喵哈哈村的大明星--星星小姐.为什么度度熊会喜欢星星小姐呢?首先星星小姐笑起来非常动人,其次星星小姐唱歌也非常好听.但这都不是最重要的,最重要的是,星星小姐拍的一手好代码!于是度度熊关注了星星小姐的贴吧.一开始度度熊决定每天都在星星小姐的贴吧里面签到.但是度度熊是一个非常健忘的孩子,总有那么几天,度度熊忘记签到,于是就断掉了他的连续签到.不过

用双指针实现PLC堆栈设计

关键技术:PLC 堆栈 关键算法:指针 某基地在设计MES现场调度模块时,架构了一个部署在车间现场的IT PLC,作为MES与ME PLC通讯的中间介质,用于处理握手信号并缓存业务数据. 此调度模块要实现以下业务数据的缓存:订单缓存.过站记录缓存.在制品队列缓存.其中订单缓存用于上线,过站记录缓存用于物料拉动,在制品队列缓存用于防错. 缓存的意义是为了防止应用系统环境(应用服务器/数据库/OPC/消息队列服务器)对现场(OEM PLC)作业的影响,毕竟PLC层面的交互要稳定及时得多. 从IT的层

【BZOJ2096】[Poi2010]Pilots 双指针+单调队列

[BZOJ2096][Poi2010]Pilots Description Tz又耍畸形了!!他要当飞行员,他拿到了一个飞行员测试难度序列,他设定了一个难度差的最大值,在序列中他想找到一个最长的子串,任意两个难度差不会超过他设定的最大值.耍畸形一个人是不行的,于是他找到了你. Input 输入:第一行两个有空格隔开的整数k(0<=k<=2000,000,000),n(1<=n<=3000,000),k代表Tz设定的最大值,n代表难度序列的长度.第二行为n个由空格隔开的整数ai(1&