Leetcode Problem 汇总一

此文章内的所有题目选自Leetcode,实现语言为Python && C++.

地址:http://oj.leetcode.com/


第一题:

Triangle

地址:http://oj.leetcode.com/problems/triangle/

分析:题目要求O(n)的内存,简单DP问题,自下而上。

代码:

class Solution:
    # @param triangle, a list of lists of integers
    # @return an integer
    def minimumTotal(self, triangle):
        tri_len = len(triangle)
        i = tri_len - 2
        while i >= 0 :
            ele_len = len(triangle[i])
            for j in range(ele_len):
                triangle[i][j] = min(triangle[i+1][j],triangle[i+1][j+1]) + triangle[i][j]
            i = i-1
        return triangle[0][0]


第二题:

Gray Code

地址:oj.leetcode.com/problems/gray-code/

分析:求格雷码,格雷码是有规律的,比如4位二进制格雷码,则从右向左,第一位上变化规律为0110,第二位变化规律00111100,以此推之。

代码:

class Solution:
    # @return a list of integers
    def work(self, pos, time):
        count = int(1)
        for i in range(pos):
            count = count*2
        time = time % (count*2)
        if time <= count/2:
            return 0
        elif time > count/2 and time <= (count+count/2):
            return 1
        return 0 
    
    def grayCode(self, n):
        ans = []
        count = int(1)
        for i in range(n):
            count = count*2
        for i in range(count):
            num = int(0)
            for j in range(n):
                num = num*2 + Solution.work(self, n-j, i+1)
            ans.append(num)
        return ans

第三题:

Maximum Depth of Binary Tree

地址:http://oj.leetcode.com/problems/maximum-depth-of-binary-tree/

分析:求树的深度,递归即可。

代码:(C++版本)

class Solution {
public:
    int max;
    void dfs(TreeNode *root, int depth)
    {
        if(root->left == NULL && root->right == NULL)
        {
            if( depth > max )
                max = depth;
            return ;
        }
        if( root->left != NULL )
        {
            dfs( root->left, depth+1);
        }
        if( root->right != NULL )
        {
            dfs( root->right, depth+1);
        }
    }
    int maxDepth(TreeNode *root) {
		if( root == NULL ) return 0;
		max = 0;
        dfs(root,1);
        return max;
    }
};

第四题:

Add Two Numbers

地址:http://oj.leetcode.com/problems/add-two-numbers/

分析:主要考察链表的使用

代码(C++版本):

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
		struct ListNode *ans(0), *ok(0);
		int num, num1, num2, pre = 0;
		ok = ( struct ListNode * )malloc( sizeof( struct ListNode ));
		ans = ( struct ListNode * )malloc( sizeof( struct ListNode ));
		ok->next = ans;
		ans->val = 0;
		while( 1 )
		{
			if( l1 == NULL && l2 == NULL ) break;
			num1 = num2 = num = 0;
			if( l1 != NULL )
			{
				num1 = l1->val;
				l1 = l1->next;
			}
			if( l2 != NULL )
			{
				num2 = l2->val;
				l2 = l2->next;
			}
			num = num1 + num2 + ans->val;
			pre = num/10;
			ans->val = num%10;
			if(( l1 != NULL || l2 != NULL ) || ( pre != 0 ) )
			{
				struct ListNode *add;
				add = ( struct ListNode * )malloc( sizeof( struct ListNode) );
				add->val = 0, add->next = NULL;
				add->val = pre;
				ans->next = add;
				ans = ans->next;
			}
		}

		return ok->next;
    }
};

python版本:

# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
    self.val = x
    self.next = None

class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        ans = ListNode()
        ok = ListNode()
        ok.next = ans
        num = 0
        pre = 0
        while true:
            if l1 == None and l2 == None:
                break
            num1 = num2 = num = int(0)
            if l1 != None:
                num1 = l1.val
                l1 = l1.next
            if l2 != None:
                num2 = l2.val
                l2 = l2.next
            num = num1 + num2 + ans.val
            pre = num//10
            ans.val = num % 10
            if l1 != None or l2 != None or pre != 0:
                add = ListNode()
                add(0)
                add.val = pre
                ans.next = add
                ans = ans.next
        return ok.next

第五题:

Merge Sorted Array

地址:http://oj.leetcode.com/problems/merge-sorted-array/

分析:挺简单的一个,two pointers算法

代码:

(C++版)

class Solution 
{
public:
    void merge(int A[], int m, int B[], int n) 
    {
        int i, j, cnt = 0;

        for( i = m-1; i >= 0; i-- )
            A[n+i] = A[i];
        for( i = 0, j = 0;; )
        {
            if(i == m || j == n) break;
            if(A[i+n] < B[j])
            {
                A[cnt] = A[i+n];
                i += 1;
            }
            else
            {
                A[cnt] = B[j];
                j += 1;
            }
            cnt += 1;
        }
        if(i < m)
        {
            for(; i < m; i++)
                A[cnt] = A[i+n], cnt += 1;
        }
        if(j < n)
        {
            for(; j < n; j++ )
                A[cnt] = B[j], cnt += 1;
        }
    }
};

(Python版)

class Solution:
    # @param A  a list of integers
    # @param m  an integer, length of A
    # @param B  a list of integers
    # @param n  an integer, length of B
    # @return nothing
    def merge(self, A, m, B, n):
        i = m-1
        cnt = int(0)
        while i >= 0:
            A[n+i] = A[i]
            i = i-1
        i = int(0)
        j = int(0)
        while 1:
            if i == m or j == n:
                break
            if A[i+n] < B[j]:
                A[cnt] = A[i+n]
                i += 1
            else:
                A[cnt] = B[j]
                j += 1
            cnt += 1
        while i < m:
            while i < m:
                A[cnt] = A[i+n]
                cnt += 1
                i += 1
        while j < n:
            A[cnt] = B[j]
            cnt += 1
            j += 1

第六题:

First Missing Positive

地址:http://oj.leetcode.com/problems/first-missing-positive/

分析:用C++写的时候直接用了个常量大小的数组,但是在用python写的时候就不行了,总是TLE,所以没用常量大小的list

代码:

(C++版)

class Solution 
{
public:
    int firstMissingPositive(int A[], int n) 
	{
        int ans, visit[100000], i;
		for( i = 0; i < 100000; i++ )
			visit[i] = 0;
		ans = 1;
		for( i = 0; i < n; i++ )
		{
			if( A[i] > 0 && A[i] < 100000) visit[A[i]] = 1;
			if( visit[ans] == 1 || A[i] == ans )
			{
				while( visit[ans] == 1)
				{
					ans += 1;
				}
			}
		}
		return ans;
    }
};
(Python版):

class Solution:
    # @param A, a list of integers
    # @return an integer
    def firstMissingPositive(self, A):
        visit = []
        for i in range(1000000):
            visit.append(0)
        ans = 1
        for i in range(len(A)):
            if A[i] > 0 or A[i] < 1000000:
                visit[A[i]] = 1
            if visit[ans] == 1 or A[i] == ans:
                while visit[ans] == 1:
                    ans += 1
        return ans

第七题:

Binary Tree Level Order Traversal

地址:http://oj.leetcode.com/problems/binary-tree-level-order-traversal/

分析:用了两个标记,一个是depth,一个是num.

代码:

(C++版)

typedef struct Node
{
	int depth;
	int value;
	int num;
}Node;

class Solution 
{
public:
	vector< Node > ans;
	int number;
	void dfs( int depth, TreeNode *root )
	{
		if( root == NULL ) return;
		Node add;
		add.depth = depth;
		add.value = root->val;
		add.num = number++;
		ans.push_back( add );
		if( root->left != NULL ) dfs( depth+1, root->left );
		if( root->right != NULL ) dfs( depth+1, root->right );
	}
	static bool cmp ( const Node &a, const Node &b )
	{
		if( a.depth != b.depth)
			return a.depth < b.depth;
		return a.num < b.num;
	}
	
    vector<vector<int> > levelOrder(TreeNode *root) 
	{
		int max, i, j;
		vector< vector < int > > ret;
		
		number = 0;
		if( root == NULL ) return ret;
		dfs( 1, root );
		sort( ans.begin(), ans.end(), cmp );
		max = ans[ans.size()-1].depth;
		j = 0;
		for( i = 1; i <= max; )
		{
			vector < int > add;
			while( ans[j].depth == i )
			{
				add.push_back( ans[j].value );
				j++;
				if( j == ans.size() ) break;
			}
			i++;
			ret.push_back( add );
			if( j == ans.size() ) break;
		}
		return ret;
    }
};

python版: PS 用python写的,提交之后一直wa,然后返回wa的测试数据,我用测试数据本地测试,完全正确,不知道什么情况,我觉得没问题。

'''
Definition for a  binary tree node
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
'''

class work:
    @staticmethod
    def dfs(depth, root):
        if root == None:
            return
        add = []
        add.append(root.val)
        add.append(Solution.number)
        add.append(depth)
        Solution.ans.append(add)
        del add
        Solution.number += 1
        if root.left != None:
            work.dfs(depth+1, root.left)
        if root.right != None:
            work.dfs(depth+1, root.right)

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    number = int(0)
    ans = []
    def levelOrder(self, root):
        ret = []
        if root == None:
            return ret
        work.dfs( 1, root)
        Solution.ans.sort(key = lambda x:(x[2], x[1]))
        maxlen = Solution.ans[len(Solution.ans)-1][2]
        j = int(0)
        i = int(1)
        while i <= maxlen:
            aad = []
            while Solution.ans[j][2] == i:
                aad.append(Solution.ans[j][0])
                j += 1
                if j == len(Solution.ans):
                    break
            i += 1
            ret.append( aad )
            del aad
            if j == len(Solution.ans):
                break
        return ret

第八题:

Add Binary

地址:http://oj.leetcode.com/problems/add-binary/

分析:很简单的题目

class Solution 
{
public:
    string addBinary(string a, string b) 
	{
		string ans = "";
		int l1 = a.length(), l2 = b.length();
		int aa, bb;
		int i, j, next, cnt, num;
		num = 0, next = 0;
		for( i = l1-1, j = l2-1;;)
		{
			aa = bb = 0;
			if( i < 0 && j < 0 ) break;
			if( i >= 0 ) aa = a[i]-'0', i--;
			if( j >= 0 ) bb = b[j]-'0', j--;
			num = next + aa + bb;
			next = num/2;
			num = num%2;
			ans.push_back( char(num+'0' ));
		}
		if( next != 0 ) ans.push_back( '1' );
		string ret = "";
		l1 = ans.length();
		for( i = 0; i < l1; i++ )
			ret.push_back( ans[l1-i-1] );
		return ret;
    }
};

(python版)

class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
        l1 = len(a)
        l2 = len(b)
        i = int(l1-1)
        j = int(l2-1)
        next = int(0)
        ans = []
        while True:
            aa = bb = int(0)
            if i < 0 and j < 0: break
            if i >= 0:
                aa = int(a[i])-int('0')
                i -= 1
            if j >= 0:
                bb = int(b[j])-int('0')
                j -= 1
            num = next + aa + bb
            next = num//2
            num = num%2
            ans.append(num)
        if next != 0:
            ans.append(1)
        ret = ''
        l1 = len(ans)
        for i in range(l1):
            if ans[l1-i-1] == 1:
                ret = ret + '1'
            else:
                ret = ret + '0'
        return ret

第九题:

Pascal's Triangle

地址:http://oj.leetcode.com/problems/pascals-triangle/

分析:帕斯卡三角(杨辉三角)

(Python版)

class Solution:
    # @return a list of lists of integers
    def generate(self, numRows):
        ans = []
        add = []
        if numRows == 0:
            return ans
        if numRows == 1:
            add = [1]
            ans.append(add)
            return ans
        add.append(1)
        ans.append(add)
        add = [1,1]
        ans.append(add)
        if numRows == 2:
            return ans
        i = int(2)
        while i < numRows:
            add = [1]
            l1 = len(ans[i-1])
            for j in range(l1-1):
                add.append(ans[i-1][j]+ans[i-1][j+1])
            add.append(1)
            ans.append(add)
            i += 1
        return ans

第十题:

Merge k Sorted Lists

地址:http://oj.leetcode.com/problems/merge-k-sorted-lists/

分析: K路合并问题,最小堆实现。

(C++版)

typedef struct Node
{
	int val, index;
}Node;

class Solution
{
public:
	Node *heap;

	static int cmp( const void *a, const void *b )
	{
		Node *aa, *bb;
		aa = (Node *)a, bb = (Node *)b;
		return aa->val - bb->val;
	}
	
	ListNode *mergeKLists(vector<ListNode *> &lists) 
	{
		int size = lists.size();
		int INF = 10000000;
		struct ListNode *ans(0), *go(0);
		if(size == 0) return NULL;
		go = (ListNode *)malloc(sizeof(struct ListNode));
		ans = go;
		go->next = NULL;
		Node heap[100010];
		int i;
		for(i = 0; i < 100010; i++) heap[i].index = -1, heap[i].val = INF;
		for(i = 1; i <= size; i++)
		{
			if(lists[i-1] != NULL)
			{
				heap[i].val = lists[i-1]->val;
				heap[i].index = i-1;
			}
			else
			{
				heap[i].val = INF;
				heap[i].index = -1;
			}
		}
		qsort(heap+1, size, sizeof(Node), cmp);
		while(1)
		{
			int idx = heap[1].index;
			if(idx == -1) break;
			struct ListNode *add;
			add = (ListNode *)malloc(sizeof(ListNode));
			add->val = heap[1].val;
			add->next = NULL;
			go->next = add;
			go = go->next;
			if(lists[heap[1].index]->next != NULL)
			{
				lists[heap[1].index] = lists[heap[1].index]->next;
				heap[1].val = lists[heap[1].index]->val;
			}
			else
			{
				heap[1].val = INF;
				heap[1].index = -1;
			}
			int ii = 1;
			while(heap[ii].val > heap[ii*2].val || heap[ii].val > heap[ii*2+1].val)
			{
				if(heap[ii*2].val > heap[ii*2+1].val)
				{
					Node temp;
					temp = heap[ii];
					heap[ii] = heap[ii*2+1];
					heap[ii*2+1] = temp;
					ii = ii<<1|1;
				}
				else
				{
					Node temp;
					temp = heap[ii];
					heap[ii] = heap[ii*2];
					heap[ii*2] = temp;
					ii = ii<<1;
				}
			}
		}
		return ans->next;
	}
};

第十一题:

Candy

地址:http://oj.leetcode.com/problems/candy/

分析:简单动态规划问题

代码:

(C++版)

class Solution 
{
public:
	int ans[100000];
    int candy(vector<int> &ratings) 
	{
        int i;
		for(i = 0; i < 100000; i++)
			ans[i] = 0;
		int size = ratings.size();
		int sum;
		ans[0] = 1;
		sum = 1;
		for(i = 1; i < size; i++)
		{
			if(ratings[i] > ratings[i-1])
				sum += 1;
			else sum = 1;
			if(sum > ans[i]) ans[i] = sum;
		}
		sum = 1;
		for(i = size-2; i >= 0; i--)
		{
			if(ratings[i] > ratings[i+1])
				sum += 1;
			else sum = 1;
			if(sum > ans[i]) ans[i] = sum;
		}
		sum = 0;
		for(i = 0;i < size; i++)
			sum += ans[i];

		return sum;
    }
};

(python版)

class Solution:
    # @param ratings, a list of integer
    # @return an integer
    def candy(self, ratings):
        l1 = len(ratings)
        ans = []
        for i in range(l1):
            ans.append(0)
        sum = 1
        ans[0] = 1
        i = 1
        while i < l1:
            if ratings[i] > ratings[i-1]:
                sum += 1
            else:
                sum = 1
            if sum > ans[i]:
                ans[i] = sum
            i += 1
        sum = 1
        i = l1-2
        while i >= 0:
            if ratings[i] > ratings[i+1]:
                sum += 1
            else:
                sum = 1
            if sum > ans[i]:
                ans[i] = sum
            i -= 1
        sum = 0
        for i in range(l1):
            sum += ans[i]
        return sum

第十二题:

3Sum

地址:http://oj.leetcode.com/problems/3sum/

分析:转化为2Sum,再用two pointers算法

代码:

(C++版)

class Solution {
public:
  void twoSum(vector<int> &num, int len, vector<vector<int> > &vec, int target) {
      vec.clear();
      vector<int> tmp;
      int i=0,j=len-1;
      while(i<j) {
          if(num[i]+num[j] == target)
          {
              tmp.push_back(num[i]);tmp.push_back(num[j]);vec.push_back(tmp);tmp.clear();
              do{
                  i++;
              }while(num[i]==num[i-1]);
              do{
                  j--;
              }while(num[j]==num[j+1]);
              continue;
          }
          if(num[i]+num[j]>target)
            do{
                j--;
            }while(num[j]==num[j+1]);
          else
            do{
                i++;
            }while(num[i]==num[i-1]);
            
      }
  }
  vector<vector<int> > threeSum(vector<int> &num) {
      sort(num.begin(),num.end());
      vector<vector<int> > vecvec;
      vector<vector<int> > tmp;
      for(int i=num.size()-1;i>=2;i--) {
          if(i!=num.size()-1 && num[i]==num[i+1])
              continue;
          twoSum(num,i,tmp,-num[i]);
          for(int j=0;j<tmp.size();j++) {
              tmp[j].push_back(num[i]);
              vecvec.push_back(tmp[j]);
          }
          tmp.clear();
      }
      return vecvec;
  }
};

第十三题:

Single Number

地址:http://oj.leetcode.com/problems/single-number/

分析:异或的神奇之处正在于此处。amazing……

(C++代码):

class Solution {
public:
    int singleNumber(int A[], int n) {
        int a = A[0];
        int i = 0;
        for(i = 1; i < n; i++)
            a = A[i]^a;
        return a;
    }
};

(python代码):

class Solution:
    # @param A, a list of integer
    # @return an integer
    def singleNumber(self, A):
        a = A[0]
        l1 = len(A)
        i = 1
        while i < l1:
            a = a^A[i]
            i += 1
        return a

第十四题:

Remove Nth Node From End of List

地址:http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/

分析:基础题。

代码:

(C++版)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) 
    {
        ListNode *ans, *go(0);
        int count = 0;
        ans = head;
        while(ans != NULL)
        {
            ans = ans->next;
            count += 1;
        }
        if(count == 1 && n == 1)return NULL;
        go = (ListNode *)malloc(sizeof(ListNode));
        ans = go;
        int i = 0;
        while(head != NULL)
        {
            if(i != count-n)
            {
                ListNode *add(0);
                add = (ListNode *)malloc(sizeof(ListNode));
                add->val = head->val;
                add->next = NULL;
                head = head->next;
                go->next = add;
                go = go->next;
                i += 1;
            }
            else
            {
                head = head->next;
                i += 1;
            }
        }
        return ans->next;
    }
};

(python版):

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @return a ListNode
    def removeNthFromEnd(self, head, n):
        go = ListNode(0)
        ans = head
        count = 0
        while ans != None:
            count += 1
            ans = ans.next
        if count == 1 and n == 1:
            return None
        ans = go
        i = 0
        while head != None:
            if i != count-n:
                add = ListNode(0)
                add.val = head.val
                add.next = None
                head = head.next
                go.next = add
                go = go.next
                i += 1
            else:
                head = head.next
                i += 1
        return ans.next

第十五题:

ZigZag Conversion

地址:http://oj.leetcode.com/problems/zigzag-conversion/

分析:注意边界情况处理,比如 nRows = 1的时候。

代码:

(C++代码)

class Solution 
{
public:
    string convert(string s, int nRows) 
	{
		int i, j, len, flag;
		string ans = "";
		len = s.length();
		if(nRows >= len || nRows == 1)
            return s;
		for(j = 1; j <= len;)
		{
			ans += s[j-1];
			j += 2*(nRows-2)+2;
		}
		for(i = 2; i < nRows; i++)
		{
			flag = 0;
			for(j = i; j <= len; )
			{
				ans += s[j-1];
				if(flag == 0) j += (nRows-i-1)*2+2, flag = 1;
				else j += (i-2)*2+2, flag = 0;
			}
		}
		for(j = nRows; j <= len; )
		{
			ans += s[j-1];
			j += (nRows-2)*2+2;
		}
		
		return ans;
    }
};

(Python版)

class Solution:
    # @return a string
    def convert(self, s, nRows):
        ans = ''
        l1 = len(s)
        j = 1
        if nRows >= l1 or nRows == 1:
            return s
        while j <= l1:
            ans += s[j-1]
            j += 2*(nRows-2)+2
        i = 2
        while i < nRows:
            flag = 0
            j = i
            while j <= l1:
                ans += s[j-1]
                if flag == 0:
                    j += (nRows-i-1)*2+2
                    flag = 1
                else:
                    j += (i-2)*2+2
                    flag = 0
            i += 1
        j = nRows
        while j <= l1:
            ans += s[j-1]
            j += (nRows-2)*2+2
        return ans

第十六题:

Rotate Image

地址:http://oj.leetcode.com/problems/rotate-image/

分析:难度小,慢慢分析一下,主要就是要求原地操作。

代码:

(C++版)

class Solution 
{
public:
	int n;
	void change(vector<vector<int>> &mat, int x, int y)
	{
		int pre = mat[x][y];
		mat[x][y] = mat[n-y-1][x];
		mat[n-y-1][x] = mat[n-x-1][n-y-1];
		mat[n-x-1][n-y-1] = mat[y][n-x-1];
		mat[y][n-x-1] = pre;

	}

	void rotate(vector<vector<int> > &matrix) 
	{
		int i, j;
		
		n = matrix.size();
		for(i = 0; i < n/2; i++)
			for(j = i;j < n-i-1; j++)
				change(matrix, i, j);
    }
};


(Python版):需要返回一个List,而C++版不需要。。。

class Solution:
    # @param matrix, a list of lists of integers
    # @return a list of lists of integers
    def rotate(self, matrix):
        n = len(matrix)
        i = 0
        j = 0
        for i in range(n//2):
            j = i
            while j < n-i-1:
                pre = matrix[i][j]
                matrix[i][j] = matrix[n-y-1][x]
                matrix[n-j-1][i] = matrix[n-i-1][n-j-1]
                matrix[n-i-1][n-j-1] = matrix[j][n-i-1]
                matrix[j][n-i-1] = pre

第十七题:

Merge Two Sorted Lists

地址:oj.leetcode.com/problems/merge-two-sorted-lists/

分析:two pointers双指针

代码:

(C++版)

class Solution 
{
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) 
    {
        ListNode *ans(0), *go(0), *add(0);
		go = (ListNode *)malloc(sizeof(ListNode));
		go->next = NULL;
		ans = go;
		if(l1 == NULL && l2 == NULL) return NULL;
		while(l1 != NULL || l2 != NULL)
		{
			if(l1 == NULL || l2 == NULL)
			{
				add = (ListNode *)malloc(sizeof(ListNode));
				add->next = NULL;
				if(l1 == NULL)
				{
					add->val = l2->val;
					l2 = l2->next;
				}
				else
				{
					add->val = l1->val;
					l1 = l1->next;
				}
				go->next = add;
				go = go->next;
			}
			else
			{
				add = (ListNode *)malloc(sizeof(ListNode));
				add->next = NULL;
    			if(l1->val < l2->val)
    			{
					add->val = l1->val;
					l1 = l1->next;
    			}
    			else
    			{
					add->val = l2->val;
					l2 = l2->next;
    			}
				go->next = add;
				go = go->next;
			}
		}
		return ans->next;
    }
};

(Python版)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param two ListNodes
    # @return a ListNode
    def mergeTwoLists(self, l1, l2):
        if l1 == None and l2 == None:
            return None
        go = ListNode(0)
        ans = go
        while l1 != None or l2 != None:
            add = ListNode(0)
            add.next = None
            if l1 == None or l2 == None:
                if l1 == None:
                    add.val = l2.val
                    l2 = l2.next
                else:
                    add.val = l1.val
                    l1 = l1.next
            else:
                if l1.val < l2.val:
                    add.val = l1.val
                    l1 = l1.next
                else:
                    add.val = l2.val
                    l2 = l2.next
            go.next = add
            go = go.next

        return ans.next

第十八题:

Text Justification

地址:http://oj.leetcode.com/problems/text-justification/

分析:考虑的方面比较多,要求也比较多。慢慢分析。。

代码:

(C++版)

class Solution 
{
public:
	string work(int l)
	{
		string str = "";
		int i;
		for(i = 0; i < l; i++)
			str += " ";
		return str;
	}
    vector<string> fullJustify(vector<string> &words, int L) 
	{  
		vector<string> ans;
		int i, j, k,size, sum, len;
		int space;
		size = words.size();
		if(L == 0)
		{
		    string str = "";
		    ans.push_back(str);
		    return ans;
		}
		if(size == 1 && words[0] == "")
		{
		    string str = "";
		    str = work(L);
		    ans.push_back(str);
		    return ans;
		}
		for(i = 0; i < size;)
		{
			string str = "";
			sum = len = 0;
			for(j = i; j < size; j++)
			{
				sum += words[j].length();
				if(sum > L) break;
				else sum += 1;
				len += words[j].length();
			}
			int div;
			if(j != size) div = j-i-1;
			else div = j-i;
			if(div == 0) div = 1;
			space = (L-len)/div;
			str += words[i];
			int mod = (L-len)%div;
			if(j != size)
			{
				if(mod != 0)
					str += work(space + 1), mod -= 1;
				else str += work(space);
				for(k = i+1; k < j; k++)
				{
					str += words[k];
					if(k != j-1)
					{
						if(mod != 0) str += work(space+1), mod -= 1;
						else str += work(space);
					}
				}
			}
			else
			{
				len = 0;
				len += words[i].length();
				if(i < j-1)
					str += " ",len += 1;
				for(k = i+1; k < j; k++)
				{
					str += words[k];
					len += words[k].length();
					if(k != j-1)
						str += " ", len += 1;
				}
				str += work(L-len);
			}
			ans.push_back(str);
			i = j;
		}

		return ans;
    }
};

第十九题:

Reverse Words in a String

地址:http://oj.leetcode.com/problems/reverse-words-in-a-string/

分析:注意s= "         "这种空情况。

代码:

(C++版)

class Solution 
{
public:
	void reverseWords(string &s) 
	{
		vector<string> vec;
		int len = s.length();
		int i, j;
		string str = "";
		int flag = 0;
		for(i = 0; i < len; i++)
		{
			if(s[i] != ' ')
				str += s[i],flag = 1;
			else if(flag)
			{
				vec.push_back(str);
				str = "";
				flag = 0;
			}
		}
		if(flag) vec.push_back(str);
		string ans = "";
		int size = vec.size();
		if(size != 0)
		{
			for(i = size-1; i >= 0; i--)
			{
				ans += vec[i];
				if(i != 0) ans += " ";
			}
		}
		s = ans;
    }
};

第二十题:

Evaluate Reverse Polish Notation

地址:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/

分析:栈的用法之一。 逆波兰数。

代码:

(C++版)

class Solution
{
public:
	int evalRPN(vector<string> &tokens) 
	{
		int stack[100000];
		int pos;
		int i, j;
		pos = -1;
		int size = tokens.size();
		for(i = 0; i < size; i++)
		{
			char c = tokens[i][0];
			if(c == '+')
			{
				int ans = stack[pos] + stack[pos-1];
				pos -= 1;
				stack[pos] = ans;
			}
			else if(c == '-' && tokens[i].length() == 1)
			{
				int ans = stack[pos-1] - stack[pos];
				pos -= 1;
				stack[pos] = ans;
			}
			else if(c == '*')
			{
				int ans = stack[pos] * stack[pos-1];
				pos -= 1;
				stack[pos] = ans;
			}
			else if(c == '/')
			{
				int ans = stack[pos-1] / stack[pos];
				pos -= 1;
				stack[pos] = ans;
			}
			else
			{
				int flag = 1;
				int len = tokens[i].length();
				if(c == '-') flag = -1, j = 1;
				else j = 0;
				int add = 0;
				for(; j < len; j++)
				{
					add *= 10;
					add += tokens[i][j]-'0';
				}

				pos += 1;
				stack[pos] = add * flag;
			}
		}
		return stack[0];
	}
};



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值