zoukankan      html  css  js  c++  java
  • 第五天

    链表(Linked List)

    • 链表是有序列表

    单项链表的建立

    题目1

    给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储一位数字。
    请你将两个数相加,并以相同形式返回一个表示和的链表。
    你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
    image

    • 代码示例
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
          //尾插法建立单链表
          ListNode hand = null;
          ListNode tail = null;
          int sum;
          int addNum = 0;
          while(l1!=null||l2!=null){
              int num1 = l1 == null? 0:l1.val;
              int num2 = l2 == null? 0:l2.val;
    
              sum = num1 + num2 + addNum;
     
              if(hand == null){
                  hand = tail = new ListNode(sum%10);
              }else{
                  if(sum>=10){
                    tail.next = new ListNode(sum-10 );
                    tail = tail.next;
                  }else{
                    tail.next = new ListNode(sum);
                    tail = tail.next;
                  } 
              }
             addNum=sum/10;
             if(l1!=null)l1 = l1.next;
             if(l2!=null)l2 = l2.next;
          }
          if(addNum==1){
            tail.next = new ListNode(addNum);
            tail = tail.next;
          }
          return hand;
        }
    }
    
    总结
    主要考察对于单链表的建立
    • 1.建立头尾节点
      ListNode hand = null;
      ListNode tail = null;
      
    • 2.临时节点
      tail.next = tempLinkedNode;
      tail = tail.next;
      

    Z字型变换(感觉N更符合)

    将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

    比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

    P A H N
    A P L S I I G
    Y I R
    之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。

    代码:

    class Solution {
        public String convert(String s, int numRows) {
            int n = s.length();
            StringBuffer str = new StringBuffer();
            int cycleLen = 2*numRows-2;
            if(n==1)return s;
            for(int i=0;i<numRows;i++){//控制行数
                for(int j=0;j+i<n;j+=cycleLen){
                    str.append(s.charAt(i+j));
                    if(i!=0&&i!=numRows-1&&j + cycleLen - i<n){
                        char append=s.charAt(j+cycleLen-i);
                        str.append(append);
                    }
                }
            }
    
            return str.toString();
    
    
        }
    }
    
    • 总结
      找规律,每行顶点的数字是cycleLen=2*hang-2
      每行非顶点是 cycleLen+j个cycleLen-第i行
  • 相关阅读:
    模式识别之检索---Bag of visual word(词袋模型)
    模式识别之knn---KNN(k-nearest neighbor algorithm)--从原理到实现
    目标跟踪之meanshift---meanshift2
    图像处理之增强---图像模糊检测
    模式识别之非参数估计---非参估计中的核函数
    haproxy文章
    nginx 有关防盗链的设置
    haproxy 关闭ssl3
    navicat 在写存储过程的时候总是说语法错误
    开源的报表系统easyreport的部署
  • 原文地址:https://www.cnblogs.com/franksimon/p/14962098.html
Copyright © 2011-2022 走看看