7

leetCode解题报告5道题(一)

 3 years ago
source link: https://blog.csdn.net/ljphhj/article/details/21865025
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

比较简单的几道题,不做详细的解释,只为之后可以回头看看自己之前的代码!!

虽然几道题都比较简单,但感觉自己写得不好,希望博文如果被哪位大神看到,可以留言下写下你的做法!

题目一:

Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

AC代码:

题目二:

Binary Tree Inorder Traversal

 (考察的其实是栈的运用,非递归遍历二叉树)

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

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

   1
    \
     2
    /
   3

return [1,3,2].

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

AC代码:

题目三:

Merge Two Sorted Lists (关于两个已经排好序的链表的合并)

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

AC代码:

题目四:

Same Tree

 

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

AC代码:

题目五:

Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that yourreturned answers (both index1 and index2) are not zero-based.

You may assume that each input wouldhave exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

由于这个题目中已经说了,只有一个解,所以我们不用考虑多个解的情况了。

思路:由于暴力的方法会TLE,所以我采用了把值当成key放入到map中,而下标作为value放入map中,map.put(numbers[i], i)。

这样预处理之后,再用个for循环,把target - numbers[i] 作为 key 去map里查找“元素”,如果找到的话,判断该“元素”的value域的值是否和当前的i相等(如果不判断会WA,比如3+3=6,返回index1 = index2 = i就错了),不相等就对应把两个下标值+1赋值给index1, index2。(题目要求: returned answers (both index1 and index2) are not zero-based.)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK