1.题目描述

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:从左下开始,小,往上,大,往右。
剑桥offer系列(1~10)
class Solution {
public:
    bool Find(vector<vector<int> > array,int target) {
        
        if(array.size()==0)return false;
        int r=array.size();
        int c=array[0].size();
        int i=r-1,j=0;
        
        while(i<r&&i>-1&&j<c&&j>-1){
            
            if(array[i][j] == target)return true;
            if(array[i][j]>target){
                i--;
            }else{
                j++;
            }
        }
        return false;
        
    }
};
View Code

 

2.题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:替换空格。
剑桥offer系列(1~10)
//length为牛客系统规定字符串输出的最大长度,固定为一个常数
class Solution {
public:
    void replaceSpace(char *str,int length) {
    int i = 0;
    int j = 0;
    int nSpace = 0;
    char *pStr = NULL;
    pStr = (char*)malloc(sizeof(char)*length * 3);
    for (i = 0, j = 0; i<length; i++, j++)
    {
        if (' ' == str[i])
        {
            pStr[j] = '\%';
            pStr[++j] = '2';
            pStr[++j] = '0';
        }
        else
        {
            pStr[j] = str[i];
        }

    }
    for( i=0;i<j;i++ )
    {
      str[i] = pStr[i];
    }

    free(pStr);
    pStr = NULL;
}
};
View Code

3.题目描述

输入一个链表,从尾到头打印链表每个节点的值。 
思路:使用vector去接,然后调用逆序算法reverse(v.begin(),v.end());
剑桥offer系列(1~10)
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        
        struct ListNode* tmp = head;
        vector<int>v;
        while(tmp != NULL){
            v.push_back(tmp->val);
            tmp = tmp->next;
        }
        reverse(v.begin(),v.end());
        return v;
    }
};
View Code

 

相关文章:

  • 2022-01-03
  • 2021-11-21
  • 2021-12-29
  • 2022-01-17
  • 2021-03-30
  • 2021-10-26
  • 2021-10-20
  • 2021-05-01
猜你喜欢
  • 2021-12-02
  • 2021-11-27
  • 2021-12-05
  • 2021-12-05
  • 2021-05-09
  • 2021-10-20
  • 2021-06-25
  • 2021-07-06
相关资源
相似解决方案