Git地址
https://gitee.com/salted_fish_without_dreams/CUC_CODER
格式要求
尽量按照格式来,开头输入一个#+空格+句子就是一级标题,两个#就是二级标题,题目用一级,其他的二级,按照先前格式即可。
思路每个人都可以添加,多多益善。
每周复盘所有题目
JZ50 数组中重复的数字
描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任一一个重复的数字。 例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是2或者3。存在不合法的输入的话输出-1
示例1
输入:
[2,3,1,0,2,5,3]
返回值:
2
说明:
2或3都是对的
思路
CY
DZR
class JZ502{/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param numbers int整型一维数组* @return int整型*//*解法1* 思路:先进行排序,然后相等的自然就在一起了,从头开始遍历,如果出现两个相邻直接输出*/public static int duplicate(List<int> numbers){numbers.Sort();for (int i = 0; i < numbers.Count; i++){if (i + 1 <= numbers.Count){if (numbers[i] == numbers[i + 1]){return numbers[i];}}else{return -1;}}return -1;}/*解法2* 思路:遍历一下原list,然后新建一个数组,逐渐插入,如果发现已经有数据了,那么直接返回*/public static int duplicate2(List<int> numbers){int[] countarray = new int[numbers.Count];for (int i = 0; i < numbers.Count; i++){countarray[numbers[i]]++;if (countarray[numbers[i]] > 1){return numbers[i];}}return -1;}/*解法3* 思路:看到不重复问题,直接想到集合的一种结构---Set,这个集合不能存放重复元素* 所以组件往set里面放,放之前检测一下是不是已经存在,存在就返回*/public static int duplicate3(List<int> numbers){HashSet<int> set = new HashSet<int>();for (int i = 0; i < numbers.Count; i++){if (set.Contains(numbers[i])){return numbers[i];}else{set.Add(numbers[i]);}}return -1;}}
LG
class Solution {
public:
int duplicate(vector<int>& numbers) {
for(int v : numbers)
{
pair<set<int>::iterator,bool> r = s.insert(v);
if(!r.second)
return *(r.first);
}
return -1;
}
set<int> s;
};
LH
YLJ
public int duplicate (int[] numbers) {
//暴力解法:采用双指针循环遍历一次
// for (int i = 0; i < numbers.length - 1; i++) {
// for (int j = i + 1; j < numbers.length; j++) {
// if (numbers[i] == numbers[j]){
// return numbers[i];
// }
// }
// }
// return -1;
//解法二:采用map辅助遍历,每次将当前遍历的数字存入map之前,先进行判断,map的key中如果不存在当前遍历的数字,则存入map的key中,否则返回已存在的数字
//本质还是数组的遍历,此解法是以空间换时间的解法,一般
Map<Integer,Integer> map = new HashMap<>();
for (int number : numbers) {
if (!map.containsKey(number)) {
map.put(number, 1); //此处map的value是什么都可以,可自定义或为null
}else {
return number;
}
}
return -1;
}
JZ51 构建乘积数组
描述
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…A[i-1]A[i+1]…A[n-1]。不能使用除法。(注意:规定B[0] = A[1] A[2] … A[n-1],B[n-1] = A[0] A[1] … A[n-2];)
对于A长度为1的情况,B无意义,故而无法构建,因此该情况不会存在。
示例1
输入:
[1,2,3,4,5]
复制
返回值:复制
[120,60,40,30,24]
思路
CY
DZR
LG
//创建两个vector分别存放 B[i]左右两侧元素之积 以空间换时间
//将一次遍历可能产生的巨大计算量问题转化为二维求积的问题。
class Solution {
public:
vector<int> multiply(const vector<int>& A) {
vector<int> LeftPart(A.size(),1);
vector<int> RightPart(A.size(),1);
auto lit = LeftPart.begin();
auto ait = A.begin();
*lit = 1;
++lit;
while(lit!=LeftPart.end())//求B[i]左边i-1个元素在A矩阵中的乘积
{
*lit = *(lit-1)**(ait);
++lit;
++ait;
}
auto rit = RightPart.end()-1;
*rit = 1;
--rit;
//求B[i]右边i-1个元素在A矩阵中的乘积
do{
(*rit) = *ait**(rit+1);
--rit;
--ait;
}while(rit>= RightPart.begin());
rit = RightPart.begin();
lit = LeftPart.begin();
while(lit!=LeftPart.end())//将左右相乘存入res中返回
{
res.push_back(*lit**rit);
++lit;
++rit;
}
return res;
}
vector<int> res;
};
LH
YLJ
public int[] multiply(int[] A) {
//解题思路:采用双指针,将A数组中的数字进行相乘得到B数组中的值,如果是相同索引,则跳过,0除外
int[] B = new int[A.length];
for (int i = 0; i < B.length; i++) {
if (B[i] == 0)
B[i] = 1;
for (int j = 0; j < A.length; j++) {
if (i != 0 && i == j){
continue;
}
B[i] *= A[j];
}
}
return B;
}
JZ13 调整数组顺序使奇数位于偶数前面
描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
示例1
示例2
输入:
[2,4,6,5,7]
复制
返回值:
思路
CY
DZR
/*
* 思路1:建立两个 array.count/2 + 1 这么大的数组 arr_left、arr_right
* 然后遇到 奇数放到 arr_left,偶数放到 arr_right
* 然后清除array数组,将数据挨个放入
* 这样其实消耗有点大,每次removeat,应该是会引起arr_left等内部重新排序,这加大了时间复杂度
* 用for循环肯定就会避免上面问题,但是我懒,就这样了先
* 用for循环,这个算法应该就是时间空间都是o(n)
*/
public static List<int> reOrderArray(List<int> array)
{
if (array != null && (array.Count > 0))
{
List<int> arr_left = new List<int>();
List<int> arr_right = new List<int>();
foreach (var value in array)
{
if (value % 2 == 0)//偶数
{
arr_right.Add(value);
}
else
{
arr_left.Add(value);
}
}
array.Clear();
while (arr_left.Count > 0)
{
//这里就是依次取第一个,然后放入到array里面
array.Add(arr_left[0]);
arr_left.RemoveAt(0);
}
while (arr_right.Count > 0)
{
array.Add(arr_right[0]);
arr_right.RemoveAt(0);
}
return array;
}
else
{
return new List<int>();
}
}
/*
* 思路2:
最终目的是奇数放到左边,偶数放到右边
我们可以从左边开始数,遇到偶数就跳过,
遇到奇数,我们就要把它放到前面,放到前面哪里,
既能保持原有顺序,又能保证在所有的偶数前面。
首先肯定不能放到第一位,这样保证不了原有顺序
那么就可以立一个flag,表示下一次遇到奇数,应该把它放到哪里。
最终的结果肯定是左侧都是奇数,所以flag的设计肯定是遇到一个奇数就+1的
保证在所有偶数的前面的操作是:遇到奇数,放到flag的位置,然后把它没移动之前的位置和将要移动到的位置之间的数据都后移一下
这个空间0(1),时间O(n²)
*/
public static List<int> reOrderArray2(List<int> array)
{
int oddFlag = -1;
for (int i = 0; i < array.Count; i++)
{
if (array[i] % 2 == 1)//遇到奇数就放到flag的位置
{
oddFlag++;
int curOdd = array[i];//先保存将要移动的数据
// 如果是个奇数,就把它到flag位置的所有元素都往后移一位,
for (int j = i; j > oddFlag; j--)
{
array[j] = array[j - 1];
}
//在目标位置flag,放入该数据
array[oddFlag] = curOdd;
}
}
return array;
}
LG
//Sol.1
//这题用冒泡的思路 冒泡保证了稳定性 不会打乱相对位置
//不过复杂度太高 第7个用例会超时
class Solution {
public:
vector<int> reOrderArray(vector<int>& array) {
bool flag = false;
int i = array.size();
if (i<2) return array;
for(int j = 0;j < i; ++j)
{
vector<int>::iterator vit = array.begin();
while(vit!=array.end()-j-1)
{
if(!(*vit%2)&&*(vit+1)%2)
{
swap(*vit, *(vit+1));
flag = true;
}
vit++;
}
if (!flag)
break;
}
return array;
}
};
//Sol.2
//直接erase偶数再push_back反倒简单点
class Solution {
public:
vector<int> reOrderArray(vector<int>& array) {
auto vit = array.begin();
while(vit!=array.end())
{
if(!(*(vit)%2))
{
array2.push_back(*vit);
array.erase(vit);
}else
++vit;
}
auto vit2 = array2.begin();
while(vit2!=array2.end())
{
array.push_back(*vit2);
++vit2;
}
return array;
}
vector<int> array2;
};
LH
YLJ
public int[] reOrderArray (int[] array) {
// write code here
//解法一:本体是要将奇数移动到偶数前面,且相对位置不变,则可以对原数组进行遍历,
//可依次统计偶数的个数count,如果遍历到的数字是奇数,则向前移动count位,遍历结束即可完成
// int count = 0;
// int temp;
// for (int i = 0; i < array.length; i++) {
// int flag = array[i] % 2;
// if (flag == 0) {
// count++;
// continue;
// }
// int j = i;
// int tempcount = count;
// while (tempcount > 0) {
// temp = array[j];
// array[j] = array[j - 1];
// array[j - 1] = temp;
// tempcount--;
// j--;
// }
// }
// return array;
//解法二:重新定义两个新数组分别存放奇数和偶数,遍历原数组将奇数和偶数分别存放到对应的新
//数组中,最后在将偶数的数组添加到奇数数组中即可
int[] oddarray = new int[array.length];
int[] evenarray = new int[array.length];
int i = 0, j = 0;
for (int k : array) {
if (k % 2 == 0) {
evenarray[j] = k;
j++;
}else {
oddarray[i] = k;
i++;
}
}
int temp = 0;
while (temp < j){
oddarray[i] = evenarray[temp];
i++;
temp++;
}
return oddarray;
}
JZ7 斐波那契数列
描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。n\leq 39n≤39
示例1
示例2
输入:
[2,4,6,5,7]
复制
返回值:
思路
CY
DZR
/*解法1
* 思路:tmd连斐波数列都忘了。最简单的是建立一个int数组,这里为了养成List的习惯,用的List,
* 就不多说了
* 时间 O(n)
* 空间o(n)
*/
public static int Fibonacci(int n)
{
// 1 1 2 3 5 8
List<int> FibList = new List<int>();
FibList.Add(0);
FibList.Add(1);
for (int i = 2; i <= n; i++)
{
int number = FibList[i - 1] + FibList[i - 2];
FibList.Add(number);
}
return FibList[n];
}
/*解法2
* 思路:最经典的思路是递归。一般都是大学当例子讲递归,但是面试中,递归是个不好的解题思路
* 递归肯定要用栈,
* 时间复杂度:O(2^n)
* 空间复杂度:栈的递归空间
* 递归一个很不好的就是有大量的重复计算,上面的数组,就可以避免重复计算
*/
public static int Fibonacci2(int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return Fibonacci2(n - 1) + Fibonacci2(n - 2);
}
}
/*
* 改进版递归,用一个标识,标记一下是不是计算过了,计算过了就直接取值
* 这样就会大大减少计算量
* 时间:O(n) 级别
* 空间:O(n) 级别
*/
public static int LoopFibonacci(List<int> fib_list, int n)
{
if (n == 0||n==1)
{
return n;
}
else if (fib_list[n]>=0)
{
return fib_list[n];
}
else
{
return LoopFibonacci(fib_list,(n - 1)) + LoopFibonacci(fib_list,(n - 2));
}
}
public static int Fibonacci3(int n)
{
List<int> fib_list = new List<int>();
for (int i = 0; i < 50; i++)
{
fib_list.Add(-1);
}
return LoopFibonacci(fib_list, n);
}
/*
* 终极优化
* 完全不用创建数组
* 时间:O(n) 级别
* 空间:O(1) 级别
*/
public static int Fibonacci4(int n)
{
//1 1 2 3 5
//a b c
//1 1 2 3 5
// a b c
if (n == 1 || n == 0) return n;
int a = 0, b = 1, c = 1;
for (int i = 2; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return c;
}
LG
class Solution {
public:
int Fibonacci(int n) {
if(n == 1) return 1;
if(n == 0) return 0;
return Fibonacci(n-1)+Fibonacci(n-2);
}
};
LH
YLJ
public static int Fibonacci(int n) {
//解法一:最简单的思路,递归
// if (n == 0 || n == 1)
// return n;
//
// return Fibonacci(n - 1) + Fibonacci(n - 2);
//解法二:动态规划思路,提高了时间效率
if (n == 0 || n == 1)
return n;
int[] num = new int[n + 1];
num[0] = 0;
num[1] = 1;
for (int i = 2; i < n + 1; i++) {
num[i] = num[i - 1] + num[i - 2];
}
return num[n];
}
JZ37 数字在升序数组中出现的次数
描述
示例1
思路
CY
DZR
using System;
using System.Collections.Generic;
namespace cuc_code
{
class JZ37
{
/*解法1
* 这个题最容易想到的是暴力,直接一遍循环就可以
* 时间复杂度: O(n)
* 空间复杂度: O(1)
*/
public static int GetNumberOfK(List<int> data, int k)
{
int count = 0;
foreach (var item in data)
{
if (item == k)
{
count++;
}
}
return count;
}
/*解法2
* 看到 排序、 查找,要立马想到二分查找
* 时间复杂度: O(logn)
* 空间复杂度: O(1)
*/
public static int GetNumberOfK2(List<int> data, int k)
{
int left_index = 0;
int right_index = data.Count - 1;
int start_index = -1;
int count = 0;
while (left_index<=right_index)//这里加上等于是为了包容[3],3这种情况
{
int middle_index = (left_index + right_index) / 2;
if (k == data[middle_index])
{
start_index = middle_index;
break;
}
else if (k < data[middle_index])
{
right_index = middle_index - 1;
}
else
{
left_index = middle_index + 1;
}
}
//如果确实存在这个数
if (start_index >= 0)
{
//二分查找找到了,所以肯定有一个了
count = 1;
//去目标索引后面找找
for (int i = start_index+1; i < data.Count && k == data[i]; i++)
{
count++;
}
//去目标索引前面找找
for (int i = start_index-1; i >=0 && k == data[i]; i--)
{
count++;
}
}
return count;
}
}
}
LG
//傻逼题
//不是傻逼题 本质上是查找 可以用二分查找使时间复杂度变成logN
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
auto dit = data.begin();
int num = 0;
for(;dit!=data.end();++dit)
{
if(*dit == k)
++num;
}
return num;
}
};
//两次二分查找 找到两个边界
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
if(data.size()<1) return NULL;
int l = 0;
int r = data.size();
//找左边界
while(l<r)
{
int mid = (l+r)>>1;
if(data[mid]<k)
{
l = mid+1;
}
else r= mid;
}
int lhs = l;
l = 0;
r = data.size();
//找右边界
while(l<r)
{
int mid = (l+r)>>1;
if(data[mid]<=k)
{
l = mid+1;
}
else r= mid;
}
return r - lhs;
}
};
LH
YLJ
public static int GetNumberOfK(int [] array , int k) {
//解法一:直接遍历判断并计数
// int count = 0;
// for (int i : array) {
// if (i == k)
// count++;
// }
// return count;
//解法二:二分查找,因为是升序数组,所以采用二分查找可以极大降低时间效率,找到数字第一次出现的位置,然后向后遍历计数
//此种解法也可以采用两次二分查找,分别查找第一次和最后一次出现的位置,然后根据位置索引得出出现的次数
if (array.length == 0)
return 0;
int first = 0;
int last = array.length - 1;
int mid = 0;
while (first != last) {
mid = (first + last) / 2;
if (array[mid] < k)
first = mid + 1;
else
last = mid;
}
if (array[first] != k)
return 0;
int count = 1;
for (int i = first; i < array.length - 1; i++) {
if (array[i] != array[i + 1])
break;
count++;
}
return count;
//解法三:利用Map结构存放数组,并把相同相同数字的个数存入value,但是牛客上不支持这种Map结构
//本质上没有解法一效率高,时间和空间都要下降
// Map<Integer, Integer> map = new HashMap<>();
// for (int i : array) {
// if (!map.containsKey(i))
// map.put(i, 1);
// else
// map.put(i, map.get(i) + 1);
// }
// return map.get(k);
}
JZ28 数组中出现次数超过一半的数字
描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。你可以假设数组是非空的,并且给定的数组总是存在多数元素。1<=数组长度<=50000
示例1
输入:
[1,2,3,2,2,2,5,4,2]
示例2
输入:
[3,3,3,3,2,2,2]
返回值:
3
思路
CY
DZR
using System;
using System.Collections.Generic;
namespace cuc_code
{
class JZ28
{
/*解法1
* 看到这题,最先想到的是暴力,就是把数组中的元素,依次拿出,扔到一个键值对里,key放元素,value放此元素被放入的次数
* 然后遍历这个字典,看一下其中哪个的value值大于一半
* 时间复杂度: O(n)
* 空间复杂度: O(n)
*/
public static int MoreThanHalfNum_Solution(List<int> numbers)
{
Dictionary<int, int> dict = new Dictionary<int, int>();
foreach (var item in numbers)
{
if (dict.ContainsKey(item))
{
dict[item]++;
}
else
{
dict.Add(item, 1);
}
}
//这里之所以加1,是因为比如一共5个元素,那么mid_count = 3大于等于3才算过半,不加1的话两个也算过半了
int mid_count = numbers.Count / 2 + 1;
foreach (var item in dict)
{
if (item.Value >= mid_count)
{
return item.Key;
}
}
return -1;
}
/*解法2
* 找到超过一半的数
* 在网上看到一个很好的思路
* 1 2 1 3 1 4 1
* 如果一个数超过一半,那么他的数量减去其他任何数的总和,都是正数
*
*
* 那么就可以这样搞,立一个flag代表这个数当前就是超过一半的目标数字
* 从左往右,先把第一个数当成是目标数字。
* 在定义一个count,代表遇到这个数字的有效总次数,为什么叫有效总次数,
* 因为,遇到一个不是flag数字的数字,要去让count减去1
* 这样就模拟出了上面的那个效果
* 当count为0 的时候,代表这个数字不可能成为大于半数的数字,因为他不符合上面的定义
* 但是并没有排除这个数最后仍然是flag数字的可能
*
* 模拟上面的过程,
* 开始flag是1,count是1,
* 然后遇到2,2不等于1,count--,然后检测count等于0了
* 所以暂时认为1不能充当flag,直接让位给2
* 2的count初始化为1
* 遇到了1,1不等于2,count--,然后检测count==0,
* 然后暂时认为2不能充当flag,让位给1,
*
* 。。。。。
*
* 最后会发现运行完flag是1,因为他的count大于0
*
* 时间复杂度: O(n)
* 空间复杂度: O(1)
*/
public static int MoreThanHalfNum_Solution2(List<int> numbers)
{
int flag = numbers[0];
int count = 1;
for (int i = 1; i < numbers.Count; i++)
{
if (flag != numbers[i])
{
count--;
// 发现不符合,立马重新初始化
if (count == 0)
{
flag = numbers[i];
count = 1;
}
}
else
{
count++;
}
}
return count >= 1 ? flag : -1;
}
/*解法3
* 直接排序,中间那个肯定是超过半数的那个
* 时间复杂度: O(nlogn) 排序,涉及到排序的最低就是这个
* 空间复杂度: O(1)
*/
public static int MoreThanHalfNum_Solution3(List<int> numbers)
{
numbers.Sort();
return numbers[(numbers.Count) / 2];
}
}
}
LG
//哈希解法 利用set初始化时自动创建key的元素的特点 直接set[key]++
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
auto nit = numbers.begin();
for(;nit!= numbers.end();++nit)
{
count[*nit]++;
}
//下面这个也可以
/*
int n = 0;
for(;n<numbers.size();++n)
{
count[numbers[n]]++;
}
*/
for(auto ci : count)
{
if(ci.second> numbers.size()/2)
return ci.first;
}
return NULL;
}
map<int ,int> count;
};
//更好的解法 看了无数次但每次都想不起来的解法:
//动态规划思想 每次出现一个数字 存入Value 设count为1 下一个数字相同 count+1\
不同 则count-1 当count=0时 res清空 到最后 count>0 则 Value中存的数就是出现次数\
大于一半的数
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int count = 0;
int Value ;
auto nit = numbers.begin();
while(nit != numbers.end())
{
if(!count)
{
Value = *nit;
++count;
}
else if(Value!=*nit)
{
--count;
}
else ++count;
++nit;
}
//此时若存在大于一半出现次数的值 它会被存放在Value中
//但也可能不存在大于一半次数的值 需要做一次判断
int count2 = 0;
for(nit = numbers.begin();nit != numbers.end();++nit)
{
if(*nit == Value)
++count2;
}
return count2>numbers.size()/2?Value:NULL;
}
};
LH
YLJ
public int MoreThanHalfNum_Solution(int [] array) {
//解法一:先将数组排序,因为求的是数组中出现次数超过一半的数字,所以该数字一定会
// 出现在数组的中间位置,所以直接返回中间位置上的数字即可,该算法的效率取决于排序算法的效率
// Arrays.sort(array);
// return array[array.length / 2];
//解法二:摩尔投票法
// 采用投票法,从头开始遍历数组,票数votes初始值为0,x位标记位,
// 表示当前票数最多的数字(即出现最多的数字),如果下一位是相同数字,则votes+1,
// 如果不同,则votes-1,当votes=0,则重新开始计数,并将标记位x重新赋值,当遍历
// 完成之后,因为数组中肯定存在出现次数超过一半的数字,所以votes肯定是>0,且x标记
// 的就是出现次数最多的数字
int x = 0;
int votes = 0;
for (int i : array) {
if (votes == 0){
x = i;
}
votes += x == i ? 1 : -1;
}
return x;
}
JZ42 和为S的两个数字
描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,返回两个数的乘积最小的,如果无法找出这样的数字,返回一个空数组即可。
返回值描述:
示例1
输入:
[1,2,4,7,11,15],15
返回值:
[4,11]
思路
CY
DZR
using System;
using System.Collections;
using System.Collections.Generic;
namespace cuc_code
{
/*
* 思路:
* 两个数字相加等于要求的sum
* 首先这两个数字肯定不能是同位置的自己
* 遍历数组
* 这个题可以转化为找一个数 target 他等于 sum - array[i]
* 简化就是一个给定一个数 array[i] ,能不能在数组中找到除了array[i]之外的一个数,他两个相加是sum
* 找到完成后,就存起来,存到dict里面以便后期比较出最小的一组
* 然后遍历dic,找到最小的
* 时间复杂度:O(n)
* 空间复杂度:O(n)
*/
class JZ42
{
public static List<int> FindNumbersWithSum(List<int> array, int sum)
{
//这里选择用键值对,是因为,在寻找数组中某个值,其实用键值对是很快的,将数组中的值当做键值对的key
//键值对的value选择放入符合要求的乘积,如果不符合要求,就放入一个最大的数字,以便后期遍历找最小的
//value为什么要用ArrayList,因为int也行,懒了,就不改回去了
Dictionary<int, ArrayList> dict = new Dictionary<int, ArrayList>();
bool flag = false;
for (int i = 0; i < array.Count; i++)
{
int target = sum - array[i];
if (dict.ContainsKey(target))//如果已经在字典中发现了目标值已经存在过,说明数组中存在这样的target
{
//将value改成乘积,方便后期比较
dict[target][0] = array[i] * target;
//dict[target][1] = true;
//代表存在过,不返回空数组
flag = true;
}
else//如果没有目标在里面,就把自己放入到键值对里,等待被别人检测(还有一种做法是开始的时候就把所有的list中的数组放到dict中一份,就不用这样动态添加了)
{
dict.Add(array[i], new ArrayList { int.MaxValue, false });
}
}
if (!flag)
{
return new List<int> { };
}
int min_product = int.MaxValue;
KeyValuePair<int, ArrayList> temp_item = new KeyValuePair<int, ArrayList>();
//查找最大的一个键值对
foreach (var item in dict)
{
int temp1 = (int)item.Value[0];
if (temp1 < min_product)
{
min_product = temp1;
temp_item = item;
}
}
return new List<int> { temp_item.Key, sum - temp_item.Key };
}
//解法2
/*
* 上面那种解法有点过于复杂了。
* 因为没有看到这个题的条件是,数组有序!!!
* 数组有序的就相对好解决
* 有序会满足以下几个准则:
* 双指针,外层相加如果小于目标值sum
* 那么就讲左边界右移一位
* 否则讲左边界右移一位
* 这就很巧妙,还是看答案知道的
* 然后如果碰到了就直接返回就行了,因为外侧的相乘肯定小于内侧
*
*/
public static List<int> FindNumbersWithSum2(List<int> array, int sum)
{
//首先定义左右的指针
int left_index = 0;
int right_index = array.Count-1;
while (left_index<right_index)
{
if (array[left_index]+array[right_index] == sum)
{
return new List<int> { array[left_index], array[right_index] };
}
else if (array[left_index] + array[right_index] < sum)
{
left_index++;
}
else
{
right_index--;
}
}
return new List<int> { };
}
}
}
LG
//脑瘫解法:
/*运行时间:ms
超过0.07% 用C++提交的代码
占用内存:KB
超过20.55%用C++提交的代码*/
//有人代码直接将乘积N设成INT_MAX,这样就不用设标志位去考虑N的初值问题
//不过设标志位的好处就是可以通过是否触发标志位判断是否存在符合条件的两个数
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
if(array.size()<2) return res;
int N ;
bool First = 1;
auto bit = array.begin();
auto cit = bit+1;
auto it1 = array.end();
auto it2 = array.end();
while(cit!=array.end())
{
bit = array.begin();
while(bit!=cit)
{
if(*bit+*cit == sum)
{
if(First)
{
N = *bit**cit;
First = 0;
it1 = bit;
it2 = cit;
}
else
if(N> *bit**cit)
{
it1 = bit;
it2 = cit;
}
break;
}else
++bit;
}
++cit;
}
if(First) return res;
res.push_back(*it1);
res.push_back(*it2);
return res;
}
vector<int> res;
};
//因为是递增队列 所以两个数相差越大 乘积就越小
//也就是最外围的解是最优解
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
if(array.size()<2) return res;
int l = 0;
int r = array.size()-1;
while(l<r)
{
if(array[l]+array[r]==sum)
{
res.push_back(array[l]);
res.push_back(array[r]);
break;
}
else if(array[l]+array[r]<sum)
++l;
else if(array[l]+array[r]>sum)
--r;
}
return res;
}
vector<int> res;
};
LH
YLJ
public static ArrayList<Integer> FindNumbersWithSum(int [] array, int sum) {
//解法一:暴力可以解决一切问题
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
//将j的初始值设为i+1,可以避免重复计算
for (int j = i + 1; j < array.length; j++) {
if (array[j] == sum - array[i]){
//其实根据升序数组的规律,我们只需要找到第一对符合条件的两个数字,此时他们的乘积就是最小
//只是针对本题目的话,以下这个判断可以省略
// if (list.size() > 0 && array[i] > list.get(0))
// continue;
list.add(array[i]);
list.add(array[j]);
//如果已经找到符合的数字,就结束内循环,寻找下一对符合条件的数字
//按照本题的要求,已经可以直接输出结果了,可以不用再继续循环寻找其他符合条件的两个数了
// break;
return list;
}
}
}
return list;
//解法二:需要对数组进行遍历,然后sum减去遍历到数字就是需要找到的数字,然后查找数组中是否存在这样的数字
//因为数组遍历时间效率较低,时间复杂度为O(n),所以可以利用HashMap,先将数组中的数字依次存入map的key,然后判断是否存在的时候
//直接用map的containsKey方法,时间复杂度为O(1)
ArrayList<Integer> list = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i : array) {
//将数组中数字当做key,出现的次数当作value
if (!map.containsKey(i))
map.put(i, 1);
else
map.put(i, map.get(i) + 1);
}
for (int i : array) {
if (map.containsKey(sum - i)) {
//此处是为了解决类似[1,4,9], 8 这种测试用例
if (i == sum - i && map.get(sum - i) == 1)
continue;
if (list.contains(i))
continue;
if (list.size() > 0 && i > list.get(0))
continue;
list.add(i);
list.add(sum - i);
}
}
return list;
}
JZ32 把数组排成最小的数
描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
示例1
输入:
[3,32,321]
CY
DZR
using System;
using System.Collections;
using System.Collections.Generic;
namespace cuc_code
{
//输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
//例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
class JZ32
{
/*
* 思路:
* 3 2 123 31
* 刚开始我的思路是,按照最大位数的那个位置,找到最小的,例如上面的,先按照1去找,发现有,就揪出来 123
* 然后在剩下的里面找, 3 2 31 还是从1开始,发现最小的是2,就揪出来 2
*
* 就是按照,第一位最小优先
* 都是最小那就按照位数少的优先
* 都一样就随便揪出一个
*
* 最后发现时间复杂度挺高的,
* while里面套遍历,起码是n的平方起步的
*
* 所以直接找答案,发现了下面的思路
* 1、全部转换为数组,因为数字位数过大,不好比较大小
* 2、将数组按照一定的规则排序
* 3、规则:两个数 '2' '123'
* 组合成为 '2123' '1232' 两个数
* 然后比较这两个字符串的大小
* 谁更小就完事了
* 时间复杂度:O(NlogN), 采用了排序
* 空间复杂度:O(N)
*/
public static string PrintMinNumber(List<int> numbers)
{
List<String> temp = new List<String>();
foreach (int item in numbers)
{
temp.Add(item.ToString());
}
//这里是匿名函数
temp.Sort((o1, o2)=> (o1 + o2).CompareTo(o2 + o1));
string result = "";
foreach (string s in temp)
{
result += s;
}
return result;
}
//思路2:最暴力的,全排列解法:
}
}
LG
//本题难点 要将int数据转化成便于比较的string类型
//比较先后顺序的思路 将ab转化为字符串 若a+b >b+a 则 b在a前
//最后设计一个比较函数 通过传参传入sort()进行排序
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
for(auto num:numbers)
{
vstr.push_back(to_string(num));
}
sort(vstr.begin(),vstr.end(),func);
string res;
for(auto ret :vstr) res+=ret;
return res;
}
//此处要用static消除this指针 以保证sort函数正常传参
bool static func(const string ls,const string rs)
{
if(ls+rs>=rs+ls)
return 0;
else return 1;
//return ls+rs<rs+ls;
}
vector<string> vstr;
};
LH
YLJ
public String PrintMinNumber(int [] numbers) {
//解法一:这道题其实就是一个按字符串排序的问题,按字典序升序排序,最后拼接起来就可以
int n;
StringBuilder s= new StringBuilder();
ArrayList<Integer> list= new ArrayList<Integer>();
n=numbers.length;
for(int i=0;i<n;i++){
list.add(numbers[i]);
}
list.sort(new Comparator<Integer>() {
public int compare(Integer str1, Integer str2) {
String s1 = str1 + "" + str2;
String s2 = str2 + "" + str1;
return s1.compareTo(s2);
}
});
for(int j:list){
s.append(j);
}
return s.toString();
}
JZ1 二维数组中的查找
描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
[
[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]
]
给定 target = 7,返回 true。
给定 target = 3,返回 false。
示例1
输入:
7,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
返回值:
true
说明:
存在7,返回true
示例2
思路
CY
DZR
LG
//两种方法 其一是从右上顶点或左下顶点沿斜对角线方向移动
//比较target与当前array中元素值大小
//若当前元素比目标大 则向原点方向移动一位
//反之 则向右下角最大值点方向移动一位
//撞墙结束 返回false
//法二待续
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int MSize = array.size();
int NSize = array[0].size();
int x = 0;
int y = NSize-1;
//从最右上角开始查找
while(x<MSize&&y>=0)
{
if(target == array[x][y])
return true;
else if(target > array[x][y])
++x;
else
--y;
}
return false;
}
};
LH
YLJ
public static boolean Find(int target, int [][] array) {
//解法一:如果暴力不是用来解题,那将毫无意义
//时间复杂度:O(m*n)
//空间复杂度: O(1)
// for (int[] ints : array) {
// for (int anInt : ints) {
// if (anInt == target)
// return true;
// }
// }
// return false;
//解法二:将二位数组按行拆分成一维数组,对每行数组进行二分查找
//时间复杂度:O(mlog(n))
//空间复杂度: O(n)
// if (array.length == 0 || array[0].length == 0)
// return false;
// for (int[] ints : array) {
// int left = 0;
// int right = ints.length - 1;
// int mid;
// while (left != right){
// mid = (left + right) / 2;
// if (ints[mid] < target)
// left = mid + 1;
// else
// right = mid;
// }
// if (ints[left] == target)
// return true;
// }
// return false;
/**
* 解法三:也是二分查找的思想,不过是对整个二位数组进行二分,因为数组
* 的特点是从左往右,从上到下都是递减,所有可以右上角元素val开始查找,如果
* target < val,则代表target是在第一行第一列的左边,于是可以将val左移一位,
* 继续判断;如果target > val,则代表target在第一行第一列的下边,则将val向下
* 移动一位,再进行判断;循环几次,直到找到target元素位置
* 时间复杂度:O(m+n)
* 空间复杂度: O(1)
*/
int i = 0;
int j = array[0].length - 1;
while (i < array.length && j >= 0){
int val = array[i][j];
if (target == val)
return true;
else if (target < val)
j--;
else i++;
}
return false;
}
JZ4 重建二叉树
描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
示例1
输入:
[1,2,3,4,5,6,7],[3,2,4,1,6,5,7]
返回值:
{1,2,5,3,4,6,7}
CY
DZR
LG
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//本题需要重建二叉树 考察二叉树逻辑结构 树节点的相关操作以及递归
//通过中序遍历加先序或后序其中一种 就可以推出完整二叉树
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(!pre.size())
return NULL;
vector <int> preLeft,preRight,vinLeft,vinRight;
TreeNode * root = new TreeNode (pre[0]);
int n = 0;
while(pre[0]!=vin[n])
{
++n;
}
for(int i = 0;i<n ;++i)
{
vinLeft.push_back(vin[i]);
preLeft.push_back(pre[i+1]);
}
for(int i = n+1; i< vin.size();++i)
{
vinRight.push_back(vin[i]);
preRight.push_back(pre[i]);
}
root->left = reConstructBinaryTree(preLeft, vinLeft);
root->right = reConstructBinaryTree(preRight, vinRight);
return root;
}
};
LH
YLJ
JZ19 顺时针打印矩阵
描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵:
[[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
则依次打印出数字
[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
示例1
思路
CY
DZR
LG
//每一圈是一个循环 也可以用递归 待其他人续
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
int m = matrix.size();
int n = matrix[0].size();
if(!m&&!n) return res;
/*if(m*n == 1) {
res.push_back(matrix[0][0]);
return res;
}*/
int count = 0;
//短边的长度与圈数存在联系
while(m-1>2*count&&n-1>2*count)
{
for(int i = count;i<n-1-count;++i)
res.push_back(matrix[count][i]);
for(int i = count;i<m-count-1;++i)
res.push_back(matrix[i][n-count-1]);
for(int i = n-1-count;i>count;--i)
res.push_back(matrix[m-count-1][i]);
for(int i = m-1-count;i>count;--i)
res.push_back(matrix[i][count]);
++count;
}
//当边为奇数的正方形 会留有一个中心点的值没有被遍历到
if((m-2*count)*(n-2*count)==1) res.push_back(matrix[count][count]);
else //当短边为奇数 会留有一排值没有被遍历到
if((m-1)==2*count)
{
for(int i = count;i<n-count;++i)
res.push_back(matrix[count][i]);
}else
if((n-1)==2*count)
{
for(int i = count;i<m-count;++i)
res.push_back(matrix[i][n-count-1]);
}
return res;
}
vector<int>res;
};
LH
YLJ
public ArrayList<Integer> printMatrix(int [][] matrix) {
/**
* 简单来说,就是不断地收缩矩阵的边界
* 定义四个变量代表范围,up、down、left、right
*
* 向右走存入整行的值,当存入后,该行再也不会被遍历,代表上边界的 up 加一,同时判断是否和代表下边界的 down 交错
* 向下走存入整列的值,当存入后,该列再也不会被遍历,代表右边界的 right 减一,同时判断是否和代表左边界的 left 交错
* 向左走存入整行的值,当存入后,该行再也不会被遍历,代表下边界的 down 减一,同时判断是否和代表上边界的 up 交错
* 向上走存入整列的值,当存入后,该列再也不会被遍历,代表左边界的 left 加一,同时判断是否和代表右边界的 right 交错
*
*/
ArrayList<Integer> list = new ArrayList<>();
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return list;
}
int up = 0;
int down = matrix.length-1;
int left = 0;
int right = matrix[0].length-1;
while(true){
// 最上面一行
for(int col=left;col<=right;col++){
list.add(matrix[up][col]);
}
// 向下逼近
up++;
// 判断是否越界
if(up > down){
break;
}
// 最右边一行
for(int row=up;row<=down;row++){
list.add(matrix[row][right]);
}
// 向左逼近
right--;
// 判断是否越界
if(left > right){
break;
}
// 最下面一行
for(int col=right;col>=left;col--){
list.add(matrix[down][col]);
}
// 向上逼近
down--;
// 判断是否越界
if(up > down){
break;
}
// 最左边一行
for(int row=down;row>=up;row--){
list.add(matrix[row][left]);
}
// 向右逼近
left++;
// 判断是否越界
if(left > right){
break;
}
}
return list;
}
JZ2 替换空格
描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
输入描述:
示例1
输入:
“We Are Happy”
返回值:
“We%20Are%20Happy”
CY
DZR
LG
LH
YLJ
public static String replaceSpace (String s) {
/**
* 解法一:遍历字符串,利用StringBuilder的特性拼接字符串,遇到空格就替换为%20
* 时间复杂度:O(n)
* 空间复杂度:O(n)
*/
StringBuilder sbr = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (" ".equals(String.valueOf(s.charAt(i))))
sbr.append("%20");
else
sbr.append(s.charAt(i));
}
return sbr.toString();
}
JZ43 左旋转字符串
描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列 S,请你把其循环左移 K 位后的序列输出(保证 K 小于等于 S 的长度)。例如,字符序列S=”abcXYZdef”,要求输出循环左移 3 位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
输入描述:
示例1
输入:
“abcXYZdef”,3
返回值:
“XYZdefabc”
CY
DZR
LG
LH
YLJ
public static String LeftRotateString(String str, int n) {
/**
* 解法一:暴力解法
* 时间复杂度:O(n^2)
* 空间复杂度:O(1)
*
*/
// char temp;
// char[] chars = str.toCharArray();
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < chars.length - 1; j++) {
// temp = chars[j];
// chars[j] = chars[j + 1];
// chars[j + 1] = temp;
// }
// }
// return String.valueOf(chars);
/**
* 解法二:其实就是把前n位的字符拼接到后面,那就直接分别截取前n位和后n位的字符串,
* 然后再反过来拼一下就完事了
* 时间复杂度:O(1)
* 空间复杂度:O(1)
*/
if ("".equals(str) || null == str)
return str;
String s1 = str.substring(0, n);
String s2 = str.substring(n);
return s2 + s1;
}
JZ54 字符流中第一个不重复的字符
描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。
后台会用以下方式调用Insert 和 FirstAppearingOnce 函数
string caseout = “”;
1.读入测试用例字符串casein
2.如果对应语言有Init()函数的话,执行Init() 函数
3.循环遍历字符串里的每一个字符ch {
Insert(ch);
caseout += FirstAppearingOnce()
}
2. 输出caseout,进行比较。
返回值描述:
示例1
CY
DZR
LG
LH
YLJ
看不懂题
JZ52 正则表达式匹配
描述
请实现一个函数用来匹配包括’.’和’‘的正则表达式。模式中的字符’.’表示任意一个字符,而’‘表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串”aaa”与模式”a.a”和”abaca”匹配,但是与”aa.a”和”ab*a”均不匹配
示例1
输入:
“aaa”,”a*a”
返回值:
true
CY
DZR
LG
LH
YLJ
不会,认栽!
JZ34 第一个只出现一次的字符
描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
示例1
CY
DZR
LG
LH
YLJ
public static int FirstNotRepeatingChar(String str) {
/**
* 解法一:利用HashMap先存储str中字符出现的次数,字符作为key,个数做为value
* 然后再遍历一次字符串,寻找出现次数是1,也就是value==1的字符,第一次找的到
* 就是结果,返回即可
* 时间复杂度:O(n)
* 空间复杂度:O(n)
*
*/
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
if (map.containsKey(str.charAt(i)))
map.put(str.charAt(i), map.get(str.charAt(i)) + 1);
else
map.put(str.charAt(i), 1);
}
for (int i = 0; i < str.length(); i++) {
if (map.get(str.charAt(i)) == 1)
return i;
}
return -1;
}
JZ53 表示数值的字符串
描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示数值。 但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。
输入描述:
示例1
示例2
输入:”1.2.3”
返回值:false
CY
DZR
LG
LH
YLJ
public static boolean isNumeric (String str) {
// write code here
/**
* 解法一:使用正则表达式匹配
* 时间复杂度:O(1)
* 空间复杂度:O(1)
*
*/
// String s = "[+-]?\\d*\\.?\\d+|[+-]?\\d*\\.?\\d+[eE][+-]?\\d+";
// return Pattern.matches(s, str);
/**
* 解法二:使用try...catch...捕获异常,这个思路挺巧的,我TM直呼NB!!!
*
*/
try {
Double res = Double.valueOf(str);
return true;
}catch (Exception e){
return false;
}
}
JZ27 字符串的排列
描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则按字典序打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
示例1
输入:
“ab”
返回值:
[“ab”,”ba”]
CY
DZR
LG
LH
YLJ
有思路,代码敲不出来,等大佬讲
JZ49 把字符串转换成整数
描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
返回值描述:
示例1
输入:”+2147483647”
返回值:2147483647
示例2
输入:”1a33”
返回值:0
CY
DZR
LG
LH
YLJ
public static int StrToInt(String str) {
//解法一:就是TMD要用库函数
// int i;
// try {
// i = Integer.parseInt(str);
// }catch (Exception e){
// return 0;
// }
// return i;
/**
* 解法二:根据ASCII码值来做,先判断第一位是不是符号位,如果是符号则先做标记,然后再
* 定义一个初始值为0的int数res,再遍历字符串根据0~9的ASCII码来判断是不是数值,如果是
* 数字则依res*10 再加上当前遍历到的数值(注意这块加的时候要减去ASCII码值与本身数值的
* 差值48),如果不是数值,则直接返回0;
* 时间复杂度:O(n)
* 空间复杂度:O(1)
*
*/
char[] chars = str.toCharArray();
int flag = -1;
int res = 0;
for (int i = 0; i < chars.length; i++) {
if (i == 0){
if (chars[i] == 43 || chars[i] == 45) {
flag = chars[i] == 43 ? 1 : 0;
continue;
}
}
if (chars[i] >= 48 && chars[i] <= 57) {
res *= 10;
res += chars[i] - 48;
}else {
return 0;
}
}
if (flag != -1)
res = flag == 1 ? res : -res;
return res;
}
JZ44 翻转单词序列
描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“nowcoder. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a nowcoder.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
示例1
输入:
“nowcoder. a am I”
返回值:
“I am a nowcoder.”
CY
DZR
LG
LH
YLJ
public static String ReverseSentence(String str) {
/**
* 解法一:按空格分割字符串,然后再把字符串数组中的字符从前往后遍历依次拼接
* 时间复杂度:O(n)
* 空间复杂度:O(n)
*/
// String[] s = str.split(" ");
// StringBuilder sbu = new StringBuilder();
// for (int i = s.length - 1; i >= 0; i--) {
// sbu.append(s[i]);
// if (i > 0)
// sbu.append(" ");
// }
// return sbu.toString();
/**
* 解法二:按空格分割字符串,然后定义双指针,分别指向数组第一位start和最后一位end,然后
* 开始循环,将双指针指向的元素交换,完成交换后start后移,end前移,当end < start时,循
* 环结束,此时数组中的元素就是正序的,再直接遍历数组拼接即可
* 其实是比第一种解法更复杂了
*
* 时间复杂度:O(n)
* 空间复杂度:O(n)
*/
String[] s = str.split(" ");
int start = 0;
int end = s.length - 1;
String temp;
while (end > start){
temp = s[start];
s[start] = s[end];
s[end] = temp;
start++;
end--;
}
StringBuilder sbu = new StringBuilder();
for (int i = 0; i < s.length; i++) {
sbu.append(s[i]);
if (i < s.length - 1)
sbu.append(" ");
}
return sbu.toString();
}
