Leetcode题目讲解汇总(持续更新)

[Leetcode1] Two Sum(两数之和)

题目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Leetcode题目讲解汇总(持续更新)_第1张图片

给了一个整数类型的数组,给一个目标数,要求在数组中找到两个整数相加正好等于目标数,且不能重复使用,返回符合要求的索引。如果采取暴力搜索的方式,遍历所有数字可能的两种组合,需要的时间复杂度为O(N^2),为了提高时间复杂度,我们可以牺牲空间,每次只遍历一个数字,另一个数字储存起来。在java中我们可以通过hashmap来实现。

Java代码:

Leetcode题目讲解汇总(持续更新)_第2张图片

 

[Leetcode2] Add Two Numbers(两数相加)

题目:

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Leetcode题目讲解汇总(持续更新)_第3张图片

这题不算难,重点是链表的建立以及进位的处理,例子中最左边是表头存放数字的低位。

java代码:

Leetcode题目讲解汇总(持续更新)_第4张图片

 

[Leetcode3] Longest Substring Without Repeating Characters(无重复字符的最长字串)

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequenceand not a substring.

Leetcode题目讲解汇总(持续更新)_第5张图片

在这里我们可以通过一个类似滑动窗口来实现,res代表无重复字符的长度,left代表滑动窗口最左边的字符,m是一个大小为256的一维数组,代表256个ASCII码。

JAVA代码:

Leetcode题目讲解汇总(持续更新)_第6张图片

你可能感兴趣的:(算法,Leetcode)