当前位置:   article > 正文

Leetcode(经典题)day3-双指针

Leetcode(经典题)day3-双指针

 验证回文串

125. 验证回文串 - 力扣(LeetCode)

直接双指针对比就行。

  1. public boolean isPalindrome(String s) {
  2. char[] arr = s.toLowerCase().toCharArray();
  3. int l=0,r=arr.length-1;
  4. while(l<r){
  5. while (l<r&&!ischar(arr[l])){
  6. l++;
  7. }
  8. while (l<r&&!ischar(arr[r])){
  9. r--;
  10. }
  11. if (arr[l++]!=arr[r--]){
  12. return false;
  13. }
  14. }
  15. return true;
  16. }
  17. public boolean ischar(char c){
  18. return (c>='0'&&c<='9')||(c>='a'&&c<='z');
  19. }

判断子序列 

392. 判断子序列 - 力扣(LeetCode)

同样使用双指针。

  1. public boolean isSubsequence(String s, String t) {
  2. int slow=0;
  3. int fast=0;
  4. while(fast<t.length()&&slow<s.length()){
  5. if(s.charAt(slow)==t.charAt(fast)){
  6. slow++;
  7. }
  8. fast++;
  9. }
  10. if(slow==s.length()){
  11. return true;
  12. }
  13. return false;
  14. }

两数之和|| 

167. 两数之和 II - 输入有序数组 - 力扣(LeetCode)

使用双指针,一个从头,一个从尾,如果当前值比target小,头指针++,如果当前值比target大,尾指针--

  1. public int[] twoSum(int[] numbers, int target) {
  2. int l=0,r=numbers.length-1;
  3. while(l<r){
  4. int res = numbers[l]+numbers[r];
  5. if(res == target){
  6. return new int[]{l+1,r+1};
  7. }else if(res > target){
  8. r--;
  9. }else{
  10. l++;
  11. }
  12. }
  13. return null;
  14. }

 盛水最多的容器

11. 盛最多水的容器 - 力扣(LeetCode)

双指针,一个从头,一个从尾,每次比较两个指针当前的所指的值,头指针小,则头指针++,尾指针小,则尾指针--,同时计算当前的面积并更新最大值。

  1. public int maxArea(int[] height) {
  2. int n = height.length;
  3. int left=0;
  4. int right=n-1;
  5. int max=(right-left)*Math.min(height[left],height[right]);
  6. while(left<right){
  7. if(height[left]<height[right]){
  8. left++;
  9. }else{
  10. right--;
  11. }
  12. int index = (right-left)*Math.min(height[left],height[right]);
  13. if(max<index){
  14. max=index;
  15. }
  16. }
  17. return max;
  18. }

三数之和

15. 三数之和 - 力扣(LeetCode)

与二数之和原理一致,多加了去重处理。

  1. if (nums.length<3){
  2. return null;
  3. }
  4. List<List<Integer>> res = new ArrayList<>();
  5. Arrays.sort(nums);
  6. int i=0;
  7. int j,k;
  8. while (i<nums.length-2){
  9. j=i+1;
  10. k=nums.length-1;
  11. while(j<k){
  12. if(nums[j]+nums[k]+nums[i]==0){
  13. List<Integer> list = new ArrayList<>();
  14. list.add(nums[i]);
  15. list.add(nums[j]);
  16. list.add(nums[k]);
  17. res.add(list);
  18. while(j<k&&nums[j+1]==nums[j]) {
  19. j++;
  20. };
  21. while(j<k&&nums[k-1]==nums[k]) {
  22. k--;
  23. };
  24. j++;
  25. k--;
  26. }else if(nums[j]+nums[k]+nums[i]>0){
  27. k--;
  28. }else {
  29. j++;
  30. }
  31. }
  32. while (i<nums.length-2&&nums[i]==nums[i+1]){
  33. i++;
  34. }
  35. i++;
  36. }
  37. return res;
  38. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/837081?site
推荐阅读
相关标签
  

闽ICP备14008679号