LeetCode_2、6两题

LeetCode_2. Add Two Numbers
原题:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

解析:复习一下链表,题目大意是将两个两个链表的数据加起来,然而这两个链表是倒着存放数字的。这就像小学数学的加法,若两对应数字相加大于等于10则进一位。因此思路比较简单,主要目的是复习链表用法。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* l1_pos = l1;
        ListNode* l2_pos = l2;
        ListNode* result_pos =new ListNode(0);
        ListNode* result = result_pos;
        int extra = 0;
        while(l1_pos || l2_pos || extra){
            int a = 0, b = 0;
            if(l1_pos != NULL){
                a = l1_pos->val;
                l1_pos = l1_pos->next;
            }
            if(l2_pos != NULL){
                b = l2_pos->val;
                l2_pos = l2_pos->next;
            }
            int sum = a + b + extra;
            extra = sum / 10;
            result_pos->next = new ListNode(sum % 10);
            result_pos = result_pos->next;
        }
        return result->next;
    }
};

感想:前几次提交都没有任何输出,最后发现是一开始初始result_pos = null,然后result = result_pos,可能result直接就置空了,所以后来改成了上述实现。

LeetCode_6. ZigZag Conversion
原题:The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P—-A—-H—-N
-A–P–L–S–I—I—G
—Y—–I——R

解析:就是将其string变成之字型排序,所以可以创建一个行数*字符串长度的二元数组,将数据填入其中,则最后逐行输出需要的字符。

class Solution {
public:
    string convert(string s, int numRows) {
        string result;
        int size = s.size();
        int row = 0,col = 0;
        int tag = 1;//tag=1->add,tag=0->sub
        vector<vector<char> > a(numRows,vector<char>(size,0));

        for(int i = 0;i < size;i++){
            a[row][col] = s[i];
            if(numRows == 1);
            else if(tag){
                if(row + 1 == numRows - 1)tag = 0;
                row ++;
            }
            else{
                if(row - 1 == 0)tag = 1;
                row--;
            }
            col++;
        }

        for(int i = 0;i < numRows;i++){
            for(int j = 0;j < size;j++){
                if(a[i][j] != 0)result += a[i][j];
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值