双指针

相向而行

  1. 反转字符串
    https://leetcode-cn.com/problems/reverse-string/solution/shuang-zhi-zhen-by-zhang-bo-b-7u4y/
class Solution {
public:
    void reverseString(vector<char>& s) {
// 0  process i,  not nkonw ,j proces end
          int i=0,j= (int)s.size()-1;
        //   相向而行
        while(i<j )
        {
            std::swap(s[i],s[j]);
            i++;
            j--;
        }
    }
};

其实同向情况难度更大

  1. 接雨水
class Solution {
public:
    int trap(vector<int>& height) {
// [0,1,0,2,1,0,1,3,2,1,2,1]
//    i   j
//        i        i 
//以最高峰为界 processed  _ unkonwn
      auto itorMax=std::max_element(height.begin(), height.end() );
      auto tMax= *itorMax;
      auto iMax= std::distance(height.begin(),  itorMax );

     int result=0;
      int i=0;
      while(height[i]  !=0 ) i++;
      int j= i+1;
      while(j<= iMax) 
      {
          if(height[j]>= height[i]) 
          {
              result += (height[j] - height[i])* (j-1-i);

             for(int s=i+1;s<j ;s++)
             {
                 result -= height[s];
             }
              i=j;
          }
          j++;
      }


       int iR= (int)height.size()-1;
       int jR= iR-1;
       while(jR>=iMax )
       {
           if(height[jR] >= height[iR])
           {
               result += (height[jR] - height[iR] ) * (iR - jR -1);
               for(int s=jR+1;s<iR;s++)
               {
                   result -= height[s];
               }
               iR= jR;

           }
            jR--;
       }
      

       return result;
       

    }
};

相关题目

posted @ 2021-11-04 11:39  boyang987  阅读(35)  评论(0编辑  收藏  举报