10大算法概念汇总(C+Java)

以下是经常用到的10个算法概念,用C和Java写的范例,之前看到一篇文章的总结,进行了参考。这些只是简单的举例,具体深入的了解还要努力去学习。

1. 字符串
2. 链表
3. 树
4. 图
5. 排序
6. 递归 vs. 迭代
7. 动态规划
8. 位操作
9. 概率问题
10. 排列组合

1. 字符串

C:

atof    (将字符串转换成浮点型数)
atoi    (将字符串转换成整型数)
atol    (将字符串转换成长整型数)
strtod (将字符串转换成浮点数)
strtol    (将字符串转换成长整型数)
strtoul  (将字符串转换成无符号长整型数)
toascii  (将整型数转换成合法的ASCII 码字符)
toupper (将小写字母转换成大写字母)
tolower  (将大写字母转换成小写字母)

Java:

toCharyArray()                  // 获得字符串对应的char数组
Arrays.sort()                     // 数组排序
Arrays.toString(char[] a)  // 数组转成字符串
charAt(int x)                    // 获得某个索引处的字符
length()                           // 字符串长度
length                             // 数组大小

2. 链表


C:

struct Node{
        int value;
        struct Node *next;
}

Java:

class Node {
    int val;
    Node next;
 
    Node(int x) {
        val = x;
        next = null;
    }
}

栈(Stack):

C:

数组实现:

struct Stack
 {
   int Array[100];
   int Top;
}; 

 void push(Stack *Stack1,int x)
 {
   Stack1->Top=Stack1->Top+1;
   Stack1->Array[Stack1->Top]=x;         
 } 

 int pop(Stack *Stack1)
 {
   if(stack_empty(Stack1))
   {
     printf("lrx");
   }
   else
   {
     Stack1->Top=Stack1->Top-1;
     return Stack1->Array[Stack1->Top+1];    
   }
 
 }

单链表实现:

typedef struct { 
   SLink top;    
   int length;
}Stack; 

 void Push ( Stack &S, ElemType e )
 {
   // 在栈顶之上插入元素 e 为新的栈顶元素
   p = new LNode;   // 建新的结点
   if(!p) exit(1);  // 存储分配失败
   p -> data = e;
   p -> next = S.top; // 链接到原来的栈顶
   S.top = p;     // 移动栈顶指针
   ++S.length;     // 栈的长度增1
 } // Push
 /*在链栈的类型定义中设立"栈中元素个数"的成员是为了便于求得栈的长度。*/
 
 bool Pop ( Stack &S, SElemType &e )
 { 
   // 若栈不空,则删除S的栈顶元素,用 e 返回其值,
   // 并返回 TRUE;否则返回 FALSE
   if ( !S.top )
     return FALSE; 
   else 
     {
       e = S.top -> data;   // 返回栈顶元素 
       q = S.top; 
       S.top = S.top -> next; // 修改栈顶指针 
       --S.length;       // 栈的长度减1 
       delete q;       // 释放被删除的结点空间
       return TRUE;
     }
 } // Pop

Java:

class Stack{
    Node top;
 
    public Node peek(){
        if(top != null){
            return top;
        }
 
        return null;
    }
 
    public Node pop(){
        if(top == null){
            return null;
        }else{
            Node temp = new Node(top.val);
            top = top.next;
            return temp;   
        }
    }
 
    public void push(Node n){
        if(n != null){
            n.next = top;
            top = n;
        }
    }
}

队列(Queue):

C:

单链表队列:

/* 单链队列——队列的链式存储结构 */
typedef struct QNode
{
  QElemType data;
  struct QNode *next;
}QNode,*QueuePtr;
 
typedef struct
{
  QueuePtr front,rear; /* 队头、队尾指针 */
}LinkQueue;
 
/* 链队列的基本操作(9个) */
void InitQueue(LinkQueue *Q)
{ /* 构造一个空队列Q */
  Q->front=Q->rear=malloc(sizeof(QNode));
  if(!Q->front)
    exit(OVERFLOW);
  Q->front->next=NULL;
}
 
void DestroyQueue(LinkQueue *Q)
{ /* 销毁队列Q(无论空否均可) */
  while(Q->front)
  {
    Q->rear=Q->front->next;
    free(Q->front);
    Q->front=Q->rear;
  }
}
 
void ClearQueue(LinkQueue *Q)
{ /* 将Q清为空队列 */
  QueuePtr p,q;
  Q->rear=Q->front;
  p=Q->front->next;
  Q->front->next=NULL;
  while(p)
  {
    q=p;
    p=p->next;
    free(q);
  }
}
 
Status QueueEmpty(LinkQueue Q)
{ /* 若Q为空队列,则返回TRUE,否则返回FALSE */
  if(Q.front->next==NULL)
    return TRUE;
  else
    return FALSE;
}
 
int QueueLength(LinkQueue Q)
{ /* 求队列的长度 */
  int i=0;
  QueuePtr p;
  p=Q.front;
  while(Q.rear!=p)
  {
    i++;
    p=p->next;
  }
  return i;
}
 
Status GetHead_Q(LinkQueue Q,QElemType *e)
{ /* 若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR */
  QueuePtr p;
  if(Q.front==Q.rear)
    return ERROR;
  p=Q.front->next;
  *e=p->data;
  return OK;
}
 
void EnQueue(LinkQueue *Q,QElemType e)
{ /* 插入元素e为Q的新的队尾元素 */
  QueuePtr p= (QueuePtr)malloc(sizeof(QNode));
  if(!p) /* 存储分配失败 */
    exit(OVERFLOW);
  p->data=e;
  p->next=NULL;
  Q->rear->next=p;
  Q->rear=p;
}
 
Status DeQueue(LinkQueue *Q,QElemType *e)
{ /* 若队列不空,删除Q的队头元素,用e返回其值,并返回OK,否则返回ERROR */
  QueuePtr p;
  if(Q->front==Q->rear)
    return ERROR;
  p=Q->front; /* 指向头结点 */
  *e=p->data;
  Q->front=p->next; /* 摘下头节点 */
  if(Q->rear==p)
    Q->rear=Q->front;
  free(p);
  return OK;
}

Java:

class Queue{
    Node first, last;
 
    public void enqueue(Node n){
        if(first == null){
            first = n;
            last = first;
        }else{
            last.next = n;
            last = n;
        }
    }
 
    public Node dequeue(){
        if(first == null){
            return null;
        }else{
            Node temp = new Node(first.val);
            first = first.next;
            return temp;
        }  
    }
}


3. 树

这里的树通常是指二叉树,每个节点都包含一个左孩子节点和右孩子节点,像下面这样:

C:

struct Tree{

        int value;

        struct Tree *left;

        struct Tree *right;

}

Java:

class TreeNode{
    int value;
    TreeNode left;
    TreeNode right;
}


下面是与树相关的一些概念:

  1. 平衡 vs. 非平衡:平衡二叉树中,每个节点的左右子树的深度相差至多为1(1或0)。
  2. 满二叉树(Full Binary Tree):除叶子节点以为的每个节点都有两个孩子。
  3. 完美二叉树(Perfect Binary Tree):是具有下列性质的满二叉树:所有的叶子节点都有相同的深度或处在同一层次,且每个父节点都必须有两个孩子。
  4. 完全二叉树(Complete Binary Tree):二叉树中,可能除了最后一个,每一层都被完全填满,且所有节点都必须尽可能想左靠。

4. 图

图相关的问题主要集中在深度优先搜索(depth first search)和广度优先搜索(breath first search)。

下面是一个简单的图广度优先搜索的实现。

1) 定义GraphNode

class GraphNode{
    int val;
    GraphNode next;
    GraphNode[] neighbors;
    boolean visited;
 
    GraphNode(int x) {
        val = x;
    }
 
    GraphNode(int x, GraphNode[] n){
        val = x;
        neighbors = n;
    }
 
    public String toString(){
        return "value: "+ this.val;
    }
}

2) 定义一个队列Queue

class Queue{
    GraphNode first, last;
 
    public void enqueue(GraphNode n){
        if(first == null){
            first = n;
            last = first;
        }else{
            last.next = n;
            last = n;
        }
    }
 
    public GraphNode dequeue(){
        if(first == null){
            return null;
        }else{
            GraphNode temp = new GraphNode(first.val, first.neighbors);
            first = first.next;
            return temp;
        }  
    }
}

3) 用队列Queue实现广度优先搜索

public class GraphTest {
 
    public static void main(String[] args) {
        GraphNode n1 = new GraphNode(1);
        GraphNode n2 = new GraphNode(2);
        GraphNode n3 = new GraphNode(3);
        GraphNode n4 = new GraphNode(4);
        GraphNode n5 = new GraphNode(5);
 
        n1.neighbors = new GraphNode[]{n2,n3,n5};
        n2.neighbors = new GraphNode[]{n1,n4};
        n3.neighbors = new GraphNode[]{n1,n4,n5};
        n4.neighbors = new GraphNode[]{n2,n3,n5};
        n5.neighbors = new GraphNode[]{n1,n3,n4};
 
        breathFirstSearch(n1, 5);
    }
 
    public static void breathFirstSearch(GraphNode root, int x){
        if(root.val == x)
            System.out.println("find in root");
 
        Queue queue = new Queue();
        root.visited = true;
        queue.enqueue(root);
 
        while(queue.first != null){
            GraphNode c = (GraphNode) queue.dequeue();
            for(GraphNode n: c.neighbors){
 
                if(!n.visited){
                    System.out.print(n + " ");
                    n.visited = true;
                    if(n.val == x)
                        System.out.println("Find "+n);
                    queue.enqueue(n);
                }
            }
        }
    }
}

Output:
value: 2 value: 3 value: 5 Find value: 5
value: 4

5. 排序

下面是不同排序算法的时间复杂度,你可以去wiki看一下这些算法的基本思想。

Algorithm Average Time Worst Time Space
冒泡排序 n^2 n^2 1
选择排序 n^2 n^2 1
Counting Sort n+k n+k n+k
Insertion sort n^2 n^2  
Quick sort n log(n) n^2  
Merge sort n log(n) n log(n) depends

6. 递归 vs. 迭代

对程序员来说,递归应该是一个与生俱来的思想(a built-in thought),可以通过一个简单的例子来说明。

问题: 有n步台阶,一次只能上1步或2步,共有多少种走法。

步骤1:找到走完前n步台阶和前n-1步台阶之间的关系。

为了走完n步台阶,只有两种方法:从n-1步台阶爬1步走到或从n-2步台阶处爬2步走到。如果f(n)是爬到第n步台阶的方法数,那么f(n) = f(n-1) + f(n-2)。

步骤2: 确保开始条件是正确的。

f(0) = 0;
f(1) = 1;

public static int f(int n){
    if(n <= 2) return n;
    int x = f(n-1) + f(n-2);
    return x;
}

递归方法的时间复杂度是n的指数级,因为有很多冗余的计算,如下:

f(5)
f(4) + f(3)
f(3) + f(2) + f(2) + f(1)
f(2) + f(1) + f(1) + f(0) + f(1) + f(0) + f(1)
f(1) + f(0) + f(1) + f(1) + f(0) + f(1) + f(0) + f(1)

直接的想法是将递归转换为迭代:

public static int f(int n) {
 
    if (n <= 2){
        return n;
    }
 
    int first = 1, second = 2;
    int third = 0;
 
    for (int i = 3; i <= n; i++) {
        third = first + second;
        first = second;
        second = third;
    }
 
    return third;
}

对这个例子而言,迭代花费的时间更少

 

7. 动态规划

动态规划是解决下面这些性质类问题的技术:

  1. 一个问题可以通过更小子问题的解决方法来解决。
  2. 有些子问题的解可能需要计算多次。
  3. 子问题的解存储在一张表格里,这样每个子问题只用计算一次。
  4. 需要额外的空间以节省时间。

爬台阶问题完全符合上面的四条性质,因此可以用动态规划法来解决。

public static int[] A = new int[100];
 
public static int f3(int n) {
    if (n <= 2)
        A[n]= n;
 
    if(A[n] > 0)
        return A[n];
    else
        A[n] = f3(n-1) + f3(n-2);//store results so only calculate once!
    return A[n];
}

8. 位操作

位操作符:

OR (|) AND (&) XOR (^) Left Shift (<<) Right Shift (>>) Not (~)
1|0=1 1&0=0 1^0=1 0010<<2=1000 1100>>2=0011 ~1=0

获得给定数字n的第i位:(i从0计数并从右边开始)

public static boolean getBit(int num, int i){
    int result = num & (1<<i);
 
    if(result == 0){
        return false;
    }else{
        return true;
    }
}

例如,获得数字10的第2位:

i=1, n=10
1<<1= 10
1010&10=10
10 is not 0, so return true;

9. 概率问题

解决概率相关的问题通常需要很好的规划了解问题(formatting the problem),这里刚好有一个这类问题的简单例子:

一个房间里有50个人,那么至少有两个人生日相同的概率是多少?(忽略闰年的事实,也就是一年365天)

计 算某些事情的概率很多时候都可以转换成先计算其相对面。在这个例子里,我们可以计算所有人生日都互不相同的概率,也就是:365/365 + 364/365 + 363/365 + 365-n/365 + 365-49/365,这样至少两个人生日相同的概率就是1 – 这个值。

public static double caculateProbability(int n){
    double x = 1;
 
    for(int i=0; i<n; i++){
        x *=  (365.0-i)/365.0;
    }
 
    double pro = Math.round((1-x) * 100);
    return pro/100;
}

calculateProbability(50) = 0.97

10. 排列组合

组合和排列的区别在于次序是否关键。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值