排序之后查找是否有前后两个相同的数字,如果有任意输出一个即可,无则输出-1
class Solution {
public:
int duplicate(vector& numbers) {
int l=numbers.size();
sort(numbers.begin(),numbers.begin()+l);
for(int i=0;i
JZ4 二维数组中的查找
二维数组中查找是否存在有目标数字,计算出二维数组的大小,遍历即可
Leecode需要多加一个判断,否则题目过不去
if(matrix.length==0||matrix[0].length==0)
return false;
class Solution {
public:
bool Find(int target, vector > array) {
int len=array.size();
int len1=array[0].size();
for(int i=0;i
JZ5 替换空格
将字符串的空格更换为%20,用一个新的字符串保存,遇到空格则保存%20,遇到其它的直接存入字符串即可
class Solution {
public:
string replaceSpace(string s) {
int l=s.length();
string s1;
int j=0;
for(int i=0;i
JZ6 从尾到头打印链表
import java.util.ArrayList;
public class Solution {
public ArrayList printListFromTailToHead(ListNode listNode) {
ArrayList list=new ArrayList<>();
while(listNode!=null){
list.add(0,listNode.val);
listNode=listNode.next;
}
return list;
}
}
JZ7 重建二叉树
给出前序遍历和中序遍历结果,求层序遍历
首先我们知道前序遍历第一个元素就是根节点,在中序遍历结果中根节点可以将中序遍历分成两段,即左子树和右子树
再进行递归,用Java中Arrays.copyOfRange函数将前序遍历的前一部分(即左子树)和中序遍历的左子树的一段递归求,同理右子树也是如此
import java.util.*;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
if(pre.length==0||vin.length==0)
return null;
//前序遍历中第一个就是根root
TreeNode root=new TreeNode(pre[0]);//前序遍历根左右
//中序遍历找到根左右分开
for(int i=0;i
JZ8 二叉树的下一个结点
class Solution {
public:
TreelinkNode* GetNext(TreelinkNode* pNode) {
if(!pNode)
return pNode;
//右孩子节点的最左孩子节点,若没有左孩子,就是自己
if(pNode->right)
{
pNode=pNode->right;
while(pNode->left)
{
pNode=pNode->left;
}
return pNode;
}
//父节点的右孩子节点
while(pNode->next){
TreelinkNode* root=pNode->next;
if(root->left==pNode)
return root;
pNode=pNode->next;
}
return nullptr;
}
};
JZ9 用两个栈实现队列
class Solution
{
public:
void push(int node) {
stack1.push(node);//尾部
}
int pop() {
//如果存储头部的栈为空,那么就把尾部的加入头部,同时删除头部栈的元素
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
int node=stack2.top();
stack2.pop();
return node;
}
private:
stack stack1;
stack stack2;
};
JZ10 斐波那契数列
class Solution {
public:
int Fibonacci(int n) {
int f[50];
f[1]=1;
f[2]=1;
for(int i=3;i<=40;i++)
f[i]=f[i-1]+f[i-2];
return f[n];
}
};
JZ11 旋转数组的最小数字
class Solution {
public:
int minNumberInRotateArray(vector rotateArray) {
int len=rotateArray.size();
int minn=99999;
for(int i=0;i
JZ14 剪绳子
n长的绳子剪为m段,计算m段绳长乘积的最大值
绳长为2,分为两段,1和1 乘积为1
绳长为3,分为两段,1和2 乘积为2
绳长为4,可以分为1 1 2和1 3和2 2,最大乘积为4
从小到大进行枚举,当我们进行求解某一个数字的时候,我们已经求出了之前的所有的数的最优的情况,那么我们可以枚举将这个数字x分解出1,2,…x-1的所有的情况,维护最大值即可
class Solution {
public:
int cutRope(int number) {
if(number<=3)
return number-1;
else
{
int f[100];
for(int i=2;i<=number;i++)
{
f[2]=2;
f[3]=3;
for(int j=1;j
JZ15 二进制中1的个数
个人认为这个更简单,容易理解
//Java代码
public class Solution {
public int NumberOf1(int n) {
String str=Integer.toBinaryString(n);//数字转换为二进制字符串
String[] str1=str.split("");//拆分函数
int ans=0;
//遍历数组,和1比较,计数即可
for(int i=0;i
JZ16 数值的整数次方
快速幂
class Solution {
public:
double Power(double base, int exponent) {
double sum=1;
int f=0;
if(exponent<0)
{
f=1;
exponent=-exponent;
}
while(exponent)
{
if(exponent%2==1){
sum*=base;
}
base=base*base;
exponent=exponent/2;
}
if(f==1)
return 1.0/sum;
else
return sum;
}
};
JZ17 打印从1到最大的n位数
这个是Java代码
import java.util.*;
public class Solution {
public int[] printNumbers (int n) {
int sum=1;
for(int i=1;i<=n;i++)
sum*=10;
int[] p = new int[sum-1];
for(int i=0;i
JZ18 删除链表的节点
import java.util.*;
public class Solution {
public ListNode deleteNode (ListNode head, int val) {
// write code here
ListNode p=null,p1=head;
while(p1!=null)
{
if(p1.val==val)//存在与val相同的值
{
if(p1==head)//如果是头指针
return head.next;//删除头指针后,头指针则变为头指针指向的下一个
p.next=p1.next;
p1.next=null;
break;
}
p=p1;
p1=p1.next;
}
return head;//返回头指针
}
}
JZ20 表示数值的字符串
Java中try catch的用法
可参考:https://blog.csdn.net/qq_34427165/article/details/83929470
try catch:自己处理异常
try {
可能出现异常的代码
} catch(异常类名A e){
如果出现了异常类A类型的异常,那么执行该代码
} …(catch可以有多个)
import java.util.*;
public class Solution {
public boolean isNumeric (String str) {
// write code here
try{
double x=Double.parseDouble(str);
return true;
}catch(Exception e){
return false;
}
}
}
JZ21 调整数组顺序使奇数位于偶数前面(一)
import java.util.*;
public class Solution {
public int[] reOrderArray (int[] array) {
// write code here
int l=array.length;
int[] arr=new int[l];
int j=0;
for(int i=0;i
JZ22 链表中倒数最后k个结点
class Solution {
public:
ListNode* FindKthToTail(ListNode* pHead, int k) {
// write code here
stackst;
ListNode *p=NULL;
while(pHead){
st.push(pHead);
pHead=pHead->next;
}
if(k>st.size()||st.size()==0)
return p;
for(int i=0;i
JZ23 链表中环的入口结点
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
sets;
while(pHead){
if(s.find(pHead)==s.end()){
s.insert(pHead);
pHead=pHead->next;
}
else {
return pHead;
}
}
return nullptr;
}
};
JZ24 反转链表
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *pre=nullptr;//pre指向反转后的最后一个节点
ListNode *cur=pHead;//cur指向反转前的第一个节点,也就是头节点pHead
ListNode *next=nullptr;//next指向反转前第二个节点保存链表,因为cur改变指向后,后面的链表则失效了,所以需要保存
while(cur){
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
};
JZ25 合并两个排序的链表
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
if(!pHead1)
return pHead2;
if(!pHead2)
return pHead1;
if(pHead1->val<=pHead2->val){
pHead1->next=Merge(pHead1->next,pHead2);
return pHead1;
}
else{
pHead2->next=Merge(pHead2->next,pHead1);
return pHead2;
}
}
};
JZ27 二叉树的镜像
class Solution {
public:
TreeNode* Mirror(TreeNode* pRoot) {
// write code here
if(pRoot==NULL)
return NULL;
TreeNode *tmp=pRoot->right;
pRoot->right=Mirror(pRoot->left);
pRoot->left=Mirror(tmp);
return pRoot;
}
};
JZ29 顺时针打印矩阵
搜索
顺序右下左上,依次遍历查询标记,注意边界即可
import java.util.ArrayList;
public class Solution {
public ArrayList printMatrix(int [][] matrix) {
int l1=matrix.length;
int l2=matrix[0].length;
boolean[][] book=new boolean[110][110];
int[] dx={0,1,0,-1};//右下左上
int [] dy={1,0,-1,0};
int tx=0,ty=0,dir=0;
ArrayListlist=new ArrayList<>();
while(tx>=0&&tx=0&&ty=0&&tx+dx[dir]=0&&ty+dy[dir]
JZ30 包含min函数的栈
获取最小值需要用两个栈来实现,一个栈存储数据,用于push和pop,另一个栈用于存储最最小值
class Solution {
public:
stacks1;//用于push和pop
stacks2;//用于存储min
void push(int value) {
s1.push(value);//放入栈中
if(s2.empty()||s2.top()>value)//栈为空或者新的元素比较小
s2.push(value);
else //新的元素比较大时,则放入栈顶元素,不放较大的新元素,所以s2.top()始终保持最小值
s2.push(s2.top());
}
void pop() {//删除操作要把两个栈中的数据都删除
s1.pop();
s2.pop();
}
int top() {//获取栈顶元素
return s1.top();
}
int min() {//获取最小元素
return s2.top();
}
};
JZ31 栈的压入、弹出序列
class Solution {
public:
bool IsPopOrder(vector pushV,vector popV) {
stackst1;
int l1=pushV.size();
int l2=popV.size();
int l3=0;
for(int i=0;i
JZ32 从上往下打印二叉树
class Solution {
public:
vector PrintFromTopToBottom(TreeNode* root) {
vectorv;
if(!root)
return v;
queueq;
q.push(root);
while(!q.empty()){
TreeNode *node=q.front();
q.pop();
v.push_back(node->val);//这里是node->val,不是node,存的是值,不是指针
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
return v;
}
};
JZ38 字符串的排列
输出全排列字符串,使用全排列函数
class Solution {
public:
vector Permutation(string str) {
sort(str.begin(),str.end());
vectorv;
v.push_back(str);//向容器尾部添加一个元素str
while(next_permutation(str.begin(),str.end())){
v.push_back(str);
}
return v;
}
};
JZ39 数组中出现次数超过一半的数字
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int[] book=new int[10010];
int l=array.length;
for(int i=0;il/2)
{
return array[i];
// break;
}
}
return 0;
}
}
JZ40 最小的K个数
代码From牛客题解区
由于个人用Java写Arrays.sort(input)总是报错改不对,用c++函数里返回一个数组写不对,所以Give up
这个代码真的很不戳啊很不戳 [赞]
class Solution {
public:
vector GetLeastNumbers_Solution(vector input, int k) {
vectorret;
if(k==0||k>input.size())
return ret;
sort(input.begin(),input.end());
return vector(input.begin(),input.begin()+k);
}
};
JZ41 数据流中的中位数
class Solution {
public:
vectorv;
void Insert(int num) {
v.push_back(num);
}
double GetMedian() {
sort(v.begin(),v.end());
if(v.size()&1)//奇数个元素
return v[(v.size()-1)/2];
else //偶数个元素
return (v[(v.size()-1)/2]+v[(v.size()-1)/2+1])/2.0;
}
};
JZ42 连续子数组的最大和
class Solution {
public:
int FindGreatestSumOfSubArray(vector array) {
int l=array.size();
int dp[200010];
dp[0]=array[0];
int maxx=dp[0];
for(int i=1;i
JZ43 整数中1出现的次数(从1到n整数中1出现的次数)
class Solution {
public:
int getf(int x){
int ans=0;
while(x){
// int s=x%10;
if(x%10==1)
ans++;
x=x/10;
}
return ans;
}
int NumberOf1Between1AndN_Solution(int n) {
int sum=0;
for(int i=1;i<=n;i++){
sum+=getf(i);
}
return sum;
}
};
JZ44 数字序列中某一位的数字
一位数[1,10) 有 数字 9个
两位数[10,100) 有 数字 90 * 2个
三位数[100,1000) 有 数字 900 * 3个
四位数[1000,10000) 有 数字 9000 * 4个…
想知道第n位所在的数字是多少,我们需要知道
给出的第n位 在哪个数里?在这个数的第几位?
如何计算?
用n不断地去减1位数的数字个数,2位数的数字个数,3位数的数字个数,减一次位数+1(记录几位数,记为digit),直到n小于需要减的数字个数,此时就可以知道他是几位数的第几个数字(即减过数字个数后的n值,)用n除以digit得出第几个数,加上num/10(即digit-1位数的最大数)即可得出第n位数字在哪个数中已知这个数,求第n位是这个数的第几位,直接用n%digit即可,如果取余结果为0,那么就是这个数的最后一位
4.注意在求第几位上是数字几的时候,是从后往前计算,一般用的是取余求该位上的数字,那么第num位就是digit-num+1,最后一位在计算过程中计算第一位,倒数第二位就是计算第二位等等…
class Solution {
public:
int findNthDigit(int n) {
if(n<10)
return n;
//digit表示位数,num表示几位数一共有几个数字
int st=1,digit=1;
long long num=9;
n=n-9;
while(n-num*digit>0)
{
n-=num*digit;
digit++;
num=num*10;
}
long long shu=n/digit+num/10;//表示第n位所在的数
long long wei=n%digit;//在数的第几位
if(wei==0)
wei=1;
else
wei=digit-wei+1;
int shu1;
while(wei--)
{
shu1=shu%10;
shu=shu/10;
}
return shu1;
}
};
JZ47 礼物的最大价值
class Solution {
public:
int maxValue(vector >& grid) {
int n=grid.size();
int m=grid[0].size();
int x,y;
int dp[210][210];
dp[1][1]=grid[0][0];
for(int i=0;i
JZ49 丑数
public class Solution {
public int GetUglyNumber_Solution(int index) {
if(index<=6)
return index;
int[] arr=new int[index];
arr[0]=1;
int a2=0,a3=0,a5=0;
for(int i=1;i
JZ50 第一个只出现一次的字符
统计所有字符出现的次数,然后查询只出现过一次的字符,遍历维护下标最小值,没有则返回-1
class Solution {
public:
int FirstNotRepeatingChar(string str) {
mapmp;
mapmp1;
for(int i=0;i='A'&&str[i]<='Z'){
mp[str[i]-'A']++;
mp1[str[i]-'A']=i;
}
else
{
mp[str[i]-'a'+27]++;
mp1[str[i]-'a'+27]=i;
}
}
int minn=999;
for(int i=0;i<52;i++)
{
if(mp[i]==1)
{
minn=min(minn,mp1[i]);
}
}
if(minn==999)
return -1;
else
return minn;
}
};
JZ52 两个链表的第一个公共结点
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode *p1=pHead1;
ListNode *p2=pHead2;
while(p1!=p2)
{
p1=p1?p1->next:pHead2;
p2=p2?p2->next:pHead1;
}
return p1;
}
};
JZ53 数字在升序数组中出现的次数
class Solution {
public:
int GetNumberOfK(vector data ,int k) {
int len =data.size();
int sum=0;
for(int i=0;i
JZ55 二叉树的深度
树的深度为 左子树深度与右子树深度的最大值+1
//c++代码
class Solution {
public:
int TreeDepth(TreeNode* pRoot) {
if(!pRoot)
return 0;
int l=TreeDepth(pRoot->left);
int r=TreeDepth(pRoot->right);
return max(l,r)+1;
}
};
JZ56 数组中只出现一次的两个数字
排序后判断其前后元素是否与自己相等,输出从小到大
//Java代码
import java.util.*;
public class Solution {
public int[] FindNumsAppearonce (int[] array){
// write code here
int[] a=new int[2];
int l=array.length,j=0;
Arrays.sort(array);
if(array[0]!=array[1])
a[j++]=array[0];
if(array[l-1]!=array[l-2])
a[j++]=array[l-1];
for(int i=1;ia[1])
{
int t=a[0];
a[0]=a[1];
a[1]=t;
}
return a;
}
}
JZ57 和为S的两个数字
class Solution {
public:
vector FindNumbersWithSum(vector array,int sum) {
int left=0,right=array.size()-1;
while(left{array[left],array[right]};
}
else if(array[left]+array[right]
JZ58 左旋转字符串
使用 substring 获取指定区间的字符串,最后拼接返回
public class Solution {
public String LeftRotateString(String str,int n) {
if (str == null || str.length()==0) {
return str;
}
n=n%str.length();
return str.substring(n) + str.substring(0, n);
}
}
JZ59 滑动窗口的最大值
class Solution {
public:
vector maxInWindows(const vector& num, unsigned int size) {
vectorv;
int pos=0;
int l=num.size();
int end=l-size+1;
if(size==0)
return v;
while(end--){
v.push_back(*max_element(num.begin()+pos,num.begin()+pos+size));
pos++;
}
return v;
}
};
JZ61 扑克牌顺子
import java.util.Arrays;
public class Solution
{
public boolean IsContinuous(int [] numbers){
Arrays.sort(numbers);
int ans=0;
for(int i=0;i<4;i++)
{
if(numbers[i]==0)
ans++;
else if(numbers[i]==numbers[i+1])
return false;
}
if(numbers[4]-numbers[ans]<5)
return true;
else
return false;
}
}
JZ62 孩子们的游戏(圆圈中最后剩下的数)
约瑟夫环问题
class Solution {
public:
int LastRemaining_Solution(int n, int m) {
int f=0;
for(int i=1;i<=n;i++){
f=(f+m)%i;
}
return f;
}
};
JZ63 买卖股票的最好时机(一)
class Solution {
public:
int maxProfit(vector& prices) {
// write code here
int minn=prices[0],profit=0;
for(int i=1;i
JZ64 求1+2+3+…+n
class Solution {
public:
int Sum_Solution(int n) {
int sum=0;
for(int i=1;i<=n;i++)
sum+=i;
return sum;
}
};
JZ65 不用加减乘除做加法
位运算
与运算(&):同1为1
0&0=0;0&1=0;1&0=0;1&1=1
或运算(|):有1为1
0|0=0; 0|1=1;1|0=1;1|1=1;
异或运算(^):不同为1
0^ 0=0; 0 ^ 1=1;1^ 0=1;1^1=0;
class Solution {
public:
int Add(int num1, int num2) {
int sum = num1 ^ num2, sum1 = (num1 & num2) << 1;
return sum + sum1;
}
};
JZ66 构建乘积数组
前缀积后缀积问题
class Solution {
public:
vector multiply(const vector& A) {
vectorv;
int l=A.size();
int sum[15],sum1[15];
sum[0]=A[0];
for(int i=1;i=0;i--){
sum1[i]=sum1[i+1]*A[i];
}
int sum2[15];
sum2[0]=sum1[1];
v.push_back(sum2[0]);
for(int i=1;i
JZ68 二叉搜索树的最近公共祖先
import java.util.*;
public class Solution {
public int CommonAncestor (TreeNode root, int p, int q) {
if(p==root.val||q==root.val)
return root.val;
if(proot.val&&q>root.val){
return CommonAncestor(root.right,p,q);
}
else
return root.val;
}
public int lowestCommonAncestor (TreeNode root, int p, int q) {
// write code here
return CommonAncestor(root,p,q);
}
}
JZ69 跳台阶
1级楼梯 1种
2级楼梯 2种
3级楼梯 3种
4级楼梯 5种
4级楼梯 8种
得出规律即可
class Solution {
public:
int jumpFloor(int number) {
if(number==1)
return 1;
else if(number==2)
return 2;
else
return jumpFloor(number-1)+jumpFloor(number-2);
}
};
JZ70 矩形覆盖
自己画画推一下规律就有了
class Solution {
public:
int rectCover(int number) {
int dp[40];
dp[1]=1,dp[2]=2;
if(number==0)
return 0;
for(int i=3;i<=38;i++)
{
dp[i]=dp[i-1]+dp[i-2];
}
return dp[number];
}
};
JZ71 跳台阶扩展问题
class Solution {
public:
int jumpFloorII(int number) {
if(number==1)
return 1;
int ans=1;
for(int i=2;i<=number;i++)
ans*=2;
return ans;
}
};
JZ73 翻转单词序列
Java字符串拆分与拼接
Leecode这么写是不对的,过不了全部的样例
for循环里面加一句Leecode就可以过完全部样例了
可能有空单词的存在就是两个单词之间有多于一个的空格
if(s1[i].equals(""))
continue;//遇到空单词跳过
public class Solution {
public String ReverseSentence(String str){
//String str="nowcoder. a am I";
String[] str1 =str.split(" ");//以空格拆分
StringBuilder str2= new StringBuilder();//StringBuilder是一个字符拼接的工具类
for(int i=str1.length-1;i>=0;i--){
str2.append(str1[i]+' ');
}
return str2.toString().trim();//toString()转换为字符串,trim()去掉两边的空格
}
}
JZ74 和为S的连续正数序列
class Solution {
public:
vector > FindContinuousSequence(int sum) {
vector>v1;
int st=1,ed=2,sn=0;
while(stsum)
st++;
else if(sn==sum){
vectorv;
for(int i=st;i<=ed;i++)
v.push_back(i);
v1.push_back(v);
ed++;
}
else
ed++;
}
return v1;
}
};
JZ75 字符流中第一个不重复的字符
class Solution
{
public:
//Insert one char from stringstream
queueq;
mapmp;
void Insert(char ch) {
if(mp.find(ch)==mp.end()){
q.push(ch);
}
mp[ch]++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce() {
while(!q.empty()){
char u=q.front();
if(mp[u]==1){
return u;
}
else
q.pop();
}
return'#';
}
};
JZ79 判断是不是平衡二叉树
public class Solution {
int flag=0;
public int depth(TreeNode root){
if(root==null)
return 0;
int l=depth(root.left);
int r=depth(root.right);
if(Math.abs(l-r)>1)
{
flag=1;
}
return Math.max(l,r)+1;
}
public boolean IsBalanced_Solution(TreeNode root) {
depth(root);
if(flag==0)
return true;
else
return false;
}
}
JZ81 调整数组顺序使奇数位于偶数前面(二)
//Java代码
import java.util.*;
public class Solution {
public int[] reOrderArrayTwo (int[] array) {
int l=array.length;
int[] a =new int[50010];
int j=0;
for(int i=0;i 

