写在前面
- Go语言中文网的站长组织了一个通过golang实现LeetCode题目的项目,每天两道,无特殊情况日日更。
- 项目代码仓库:https://github.com/studygolang/leetcode
- 仓库里有不同Coder的解题思路,可以参考其他人的思路
- 写这个系列blog的目的很简单,记录并督促自己好好刷题
001-twoSum
分类:Easy
题目
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:
1 | Given nums = [2, 7, 11, 15], target = 9, |
解题思路
利用map
- key是传入列表的元素
- value是元素的下标
- tmp是对应的元素,相加等于target
代码
1 | func twoSum(nums []int, target int) []int{ |
002-addTwoNumbers
分类:Medium
题目
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.
Example:
1 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) |
解题思路
同步遍历两个链表,对位相加并用一个变量flag记录进位,当两个列表的笑一个节点都为nil并且无进位时,返回结果
代码
1 | /** |
026-Remove Duplicates from Sorted Array
分类:Easy
题目
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
1 | Given nums = [1,1,2], |
Example 2:
1 | Given nums = [0,0,1,1,1,2,2,3,3,4], |
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
1 | // nums is passed in by reference. (i.e., without making a copy) |
解题思路
因为给定的整型数组已排序,所以不需要排序操作。这个算法有个缺点:破坏了传入数组内的数据了
代码
1 | func removeDuplicates(nums []int) int { |
027-Remove Element
分类:Easy
题目
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example 1:
1 | Given nums = [3,2,2,3], val = 3, |
Example 2:
1 | Given nums = [0,1,2,2,3,0,4,2], val = 2, |
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
1 | // nums is passed in by reference. (i.e., without making a copy) |
解题思路
和026很像,遍历数组就完事了
代码
1 | func removeElement(nums []int, val int) int { |