剑指 Offer 03. 数组中重复的数字
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:
2 <= n <= 100000
java
解题思路:
先排序在遍历,前后位置的值一样代表重复
用到的知识点:
排序sort,
Arrays.sort(nums);
class Solution {
public int findRepeatNumber(int[] nums) {
Arrays.sort(nums);
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1]){
return nums[i];
}
}
return nums[-1];
}
}
python
解题思路同上
用到的知识点:
python排序,
sorted(nums),返回一个新的lisy,需要定义新的
num = sorted(nums)
num.sort()// 不返回新的
class Solution(object):
def findRepeatNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num = sorted(nums)
for i in range(len(num)-1):
if num[i]==num[i+1]:
return num[i]
class Solution(object):
def findRepeatNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# num = sorted(nums)
nums.sort()
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
return nums[i]
剑指 Offer 04. 二维数组中的查找
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
现有矩阵 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。
限制:
0 <= n <= 1000
0 <= m <= 1000
java
解题思路;先和每行的开头结尾比较,如果比开头小或者比结尾大,那这一行就不用比了。
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix==null){
return false;
}
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
if(target<matrix[i][0] || target>matrix[i][matrix[0].length-1]){
break;
}
if(target==matrix[i][j]){
return true;
}
}
}
return false;
}
}
python
解题思路同上
class Solution(object):
def findNumberIn2DArray(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
x = len(matrix)
y = len(matrix[0])
for i in range(x):
for j in range(y):
if target<matrix[i][0] or target>matrix[i][y-1]:
break
if target == matrix[i][j]:
return True
return False
剑指 Offer 05. 替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = “We are happy.”
输出:“We%20are%20happy.”
限制:
0 <= s 的长度 <= 10000
解题思路没啥好说的,使用replace方法:
xx.replace(要替换的目标字符串,替换后的字符串)
java
class Solution {
public String replaceSpace(String s) {
return s.replace(" ","%20");
}
}
python
class Solution(object):
def replaceSpace(self, s):
"""
:type s: str
:rtype: str
"""
return s.replace(" ","%20")
剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
java
解题思路:
先获取链表长度,之后创建一个数组,把链表的各节点值按照逆序放到数组中
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
ListNode p = head;
int number = 0;
while(p!=null){
number = number + 1;
p = p.next;
}
int[] res = new int[number];
for(int i =number-1;i>-1;i--){
res[i] = head.val;
head = head.next;
}
return res;
}
}
python
解题思路:
创建一个数组,遍历链表把各个节点的值放到数组中。然后返回数组的翻转。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reversePrint(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
res = []
while head:
res.append(head.val)
head = head.next
return res[::-1]
剑指 Offer 09. 用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
[“CQueue”,“appendTail”,“deleteHead”,“deleteHead”]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
[“CQueue”,“deleteHead”,“appendTail”,“appendTail”,“deleteHead”,“deleteHead”]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
解题思路:
把插入的数放在数组A中,删除的时候,先把A全部出队列放在B数组中,返回B数组的最后一个,最后再把B数组出队列插回A数组。
java
class CQueue {
public Stack<Integer> resA;
public Stack<Integer> resB;
public CQueue() {
resA = new Stack<Integer>();
resB = new Stack<Integer>();
}
public void appendTail(int value) {
resA.push(value);
}
public int deleteHead() {
if(resA.isEmpty()){
return -1;
}
while(!resA.isEmpty()){
resB.push(resA.pop());
}
int number = resB.pop();
while(!resB.isEmpty()){
resA.push(resB.pop());
}
return number;
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
python
class CQueue(object):
def __init__(self):
self.resA = []
self.resB = []
def appendTail(self, value):
"""
:type value: int
:rtype: None
"""
self.resA.append(value)
def deleteHead(self):
"""
:rtype: int
"""
if not self.resA:
return -1
while self.resA:
self.resB.append(self.resA.pop())
number = self.resB.pop()
while self.resB:
self.resA.append(self.resB.pop())
return number
# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()
剑指 Offer 10- I. 斐波那契数列
写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:1
示例 2:
输入:n = 5
输出:5
提示:
0 <= n <= 100
java
解题思路:
利用数组,某个位置的n等于前两个数之和。
class Solution {
public int fib(int n) {
if(n==0){
return 0;
}
if(n==1){
return 1;
}
int[] res = new int[n+1];
res[0] = 0;
res[1] = 1;
for(int i=2;i<n+1;i++){
res[i] = (res[i-1] + res[i-2])%1000000007;
}
return res[n];
}
}
python
解题思路:动态规划,前一组的b,sum作为后一组的a,b求和赋值给sum。
class Solution(object):
def fib(self, n):
"""
:type n: int
:rtype: int
"""
if n==0:return 0
if n ==1:return 1
a=0
b=1
sum = 0
for i in range(2,n+1):
sum = (a+b)%1000000007
a = b
b = sum
return sum
剑指 Offer 10- II. 青蛙跳台阶问题
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:2
示例 2:
输入:n = 7
输出:21
示例 3:
输入:n = 0
输出:1
提示:
0 <= n <= 100
解题思路和上一题差不多
java
class Solution {
public int numWays(int n) {
if(n==0 || n==1){
return 1;
}
if(n==2){
return 2;
}
int[] res = new int[n+1];
res[0] = 1;
res[1] = 1;
res[2] = 2;
for(int i=3;i<n+1;i++){
res[i] = (res[i-1] + res[i-2])%1000000007;
}
return res[n];
}
}
python
class Solution(object):
def numWays(self, n):
"""
:type n: int
:rtype: int
"""
if n==0:return 1
if n ==1:return 1
if n==2:return 2
a=1
b=2
sum = 0
for i in range(3,n+1):
sum = (a+b)%1000000007
a = b
b = sum
return sum