刷过算法题汇总

按照类型分类一下,方便自己的总结和回忆,暂时不知道如何分类,所以先随意列个框架,这半年去慢慢完善好。

 

字符处理类:

(1)

题目描述:

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

输入:

每个输入文件仅包含一组测试样例。
对于每组测试案例,输入一行代表要处理的字符串。

输出:

对应每个测试案例,出经过处理后的字符串。

样例输入:
We Are Happy
样例输出:
We%20Are%20Happy
 
这一题来自剑指offer,测试用例包括完全是空的字符串能否读入,实际编程中发现有些方式纯粹空字符串无法读取。在编程过程中出现了以下两个问题:
(1)完全有空格组成的字符串无法读取,Java中的Scanner.nextLine()无法读取一个完全由空格组成的字符串,改为由InputStreamReader方式读取才可以;
(2)Java本身的效率问题,超时,无法使用String的自带方法String.replaceAll(“ ”,"%20”)。
(3)替换过程中,从尾部开始替换,一次性替换到位,这样可以保持O(n)的复杂度。
#include<string.h>
#include<stdio.h>
 
int main() {
    int i,count,len;
    int pos,newpos,hold;
    char str[1000000];
    memset(str,1000000,'\0');
    while (gets(str)!=NULL) {
        len = 0;
        count = 0;
        
        for(i=0;i<1000000 && str[i]!='\0';i++){
            if(str[i]==' '){
                count++;
            }
            len = i;
        }
        pos = len;
        newpos = len+count*2;
        hold = newpos;
        
        str[newpos+1]='\0';
        for(pos;pos>=0;pos--){
            if(str[pos]==' '){
                str[newpos-2] = '%';
                str[newpos-1] = '2';
                str[newpos] = '0';
                newpos-=3;
            }
            else{
                str[newpos--] = str[pos];
            }
        }
        
        printf("%s\n",str);
        memset(str,1000000,'\0');
    }
    return 0;
}
 

链表类:

(1)

题目描述:

输入一个链表,从尾到头打印链表每个节点的值。

输入:

每个输入文件仅包含一组测试样例。
每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。

输出:

对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。

 

使用STL里面的stack,别傻傻的自己写stack啦

#include<stdio.h>
#include<stack>
using namespace std;
 
int main(){
    int num = 0;
    int i;
    stack<int> s;
    
    scanf("%d",&num);
    while(num!=-1){
        s.push(num);
        scanf("%d",&num);
    }
 
    while(!s.empty()){
        printf("%d\n",s.top());
        s.pop();
    }
 
    return 0;
}

 

 

 

树类:

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

 

#include "main.h"
#include<iostream>   
#include<stdio.h>
#include<stdlib.h>
#include <vector> 
using namespace std;
 
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  };
 
class Solution {
public:
   public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> arr;
        arr = postorderTrave(root,arr);
        return arr;
    }
    
    vector<int> postorderTrave(TreeNode *root, vector<int> arr){
        if(root!=NULL){
            if(root->left!=NULL){
            
                arr = postorderTrave(root->left,arr);
            }
            if(root->right!=NULL){
                arr = postorderTrave(root->right,arr);
            }
                arr.push_back(root->val);
        }
        return arr;
    }
    
    
    
};
 
int main(){
 
    TreeNode head = TreeNode(1);
    TreeNode cl = TreeNode(2);
    TreeNode cr = TreeNode(3);
    head.left = &cl;
    head.right = &cr;
    
    vector<int> arr ;
    
    
    Solution s ;
    arr = s.postorderTraversal(&head);
 
    for(int i=0;i<arr.size();i++){
        cout<<arr[i]<<endl;
    }
    
    return 0;
}

 

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

 

本题需要找到所有的路径(从根节点到叶节点)。这里采用的办法遍历过程中使用一个数组来保存当前操作节点到根节点之间的序列,当确定一个点为叶子节点之后,通过路径数组来获得该条路径所对应的数,遍历一遍之后,得到sum值

#include "main.h"
#include<iostream>   
#include<stdio.h>
#include<stdlib.h>
#include <vector> 
using namespace std;
 
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  };
 
class Solution {
    
public:
   public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> arr;
        arr = postorderTrave(root,arr);
        return arr;
    }
    vector<int> postorderTrave(TreeNode *root, vector<int> arr){
        if(root!=NULL){
            if(root->left!=NULL){
            
                arr = postorderTrave(root->left,arr);
            }
            if(root->right!=NULL){
                arr = postorderTrave(root->right,arr);
            }
                arr.push_back(root->val);
        }
        return arr;
    }
    
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> arr;
        arr = preorderTrave(root,arr);
        return arr;
    }
    vector<int> preorderTrave(TreeNode *root, vector<int> arr){
        if(root!=NULL){
            arr.push_back(root->val);
            if(root->left!=NULL){
            
                arr = postorderTrave(root->left,arr);
            }
            if(root->right!=NULL){
                arr = postorderTrave(root->right,arr);
            }    
        }
        return arr;
    }
    
    int sumNumbers(TreeNode *root) {
        vector<int> path;
        int sum = 0;
        getSum(root, path, sum);
        return sum;
    }
    void getSum(TreeNode *root, vector<int> path, int &sum){
        if(root!=NULL){
            path.push_back(root->val);
            if(root->left!=NULL){
                getSum(root->left,path,sum);
            }
            if(root->right!=NULL){
                getSum(root->right,path,sum);
            }
            if(root->left==NULL && root->right==NULL){
                    int num=0;
                    int temp =1;
                    for(int i=0;i<path.size();i++){
                        num = num + path[path.size()-1-i]*temp;
                        temp *= 10;
                    }
                    sum += num;
            }
            path.pop_back();
        }
    }
};
 
int main(){
 
    TreeNode head = TreeNode(1);
    TreeNode cl = TreeNode(2);
    TreeNode cr = TreeNode(3);
    head.left = &cl;
    head.right = &cr;
    
    vector<int> arr ;
    
    
    Solution s ;
    int num = s.sumNumbers(&head);
    cout<<num<<endl;
    arr = s.postorderTraversal(&head);
 
//    for(int i=0;i<arr.size();i++){
//        cout<<arr[i]<<endl;
//    }
    
    return 0;
}

 

 

位操作:

Single Number II
Total Accepted: 14014 Total Submissions: 42933My Submissions

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

 

算法思想,与一队两个数只有一个重复基本一致。使用位运算,int数据有32位,外层循环分别统计这32个二进制值,而内层循环则统计这一队数据中1的个数,然后%3之后,剩余的余数要么为1,要么为0,即为那唯一的一个数字。

本题其实,并没有说明不是只有3个的数字具体是多少个,可能有3n+1,3n+2个,这个可以根据n进行判断

#include <cstdlib>
#include <iostream>
#include <stdlib.h>
 
using namespace std;
 
class Solution {
public:
    int singleNumber(int A[], int n) {
        int count;
        int result = 0;
        for(int i=0;i<32;i++){
                count = 0;
                for(int j=0;j<n;j++) {
                     if(((A[j]>>i) & 1 )==1){
                          count++;             
                     }          
                }       
                count = count%3;
                result = result | (count<<i); 
        }
        return result;
    }
};
posted @ 2014-04-05 20:52  CC同学哈  阅读(281)  评论(0编辑  收藏  举报