算法小题

  1. 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
    class Solution {
    public:
        bool Find(int target, vector<vector<int> > array) {
            int m = array.size();//行数
            int n = array[0].size();//列数
            int x =m-1,y=0;
              while(x >= 0 && y < n ){
                if(array[x][y] == target){
                    return true;
                }
                else if(array[x][y] > target)
                {
                    x--;
                     continue;
                }
                 else if(array[x][y] < target)
                {
                    y++;
                     continue;
                }
        }
            return false;
        }
    };
    Find
  2. 输入一个链表,从尾到头打印链表每个节点的值
    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector<int> printListFromTailToHead(ListNode* head) {
            vector<int>dev;
            if(head!=NULL)     //头不为空
            {
                dev.insert(dev.begin(),head->val);  //在vector首插入节点
                while(head->next!=NULL)    //next不为空
                {
                    dev.insert(dev.begin(),head->next->val); //next插入vector节点
                    head = head->next;  //移动节点
                }
            }
            return dev;
        }
    };
    View Code

     

  3. 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
    class Solution
    {
    public:
        void push(int node) {
            stack1.push(node);//新进的元素,压入栈1
        }
    
        int pop() {
            if(stack2.empty()&&stack1.empty()){
                //cout<<“queue is empty”
            }
            if(stack2.empty()){ //如果栈2为空
                while(!stack1.empty()){    //如果栈1不为空
                    stack2.push(stack1.top()); //把栈1的全部数据出栈,压入放入栈2
                    stack1.pop();
                }
            }
            int n = stack2.top();
                stack2.pop();
            return n;//栈2出栈
        }
    
    private:
        stack<int> stack1;
        stack<int> stack2;
    };
    View Code

     

  4. 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。测试用例为0,1,1,2,3,5。正确是不应该的有0的

    n<=39

    class Solution {
    public:
        int Fibonacci(int n) {
            int num;
            int num1 = 1;
            int num2 = 1;
            if(n == 0)
            {
                return 0 ;   
                
            }
               if(n == 1 || n==2)
            {
                return 1;    
            }
          
            for(int i = 2; i < n; ++i){
              num = num1+num2;
              num1=num2;
              num2=num;
            }
            return num;
        }
    };
    View Code

     

posted @ 2017-05-04 18:14  夜の魅  阅读(498)  评论(0编辑  收藏  举报