问题描述
我正在尝试就地反转数组,例如给定数组[1,2,3]
将其反转为[3,1]
。
这是我的实现方式:
function reverseInPlace(arr) {
var start = 0;
var end = arr.length + 1;
while (start > end) {
var temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
return arr;
};
reverseInPlace([1,3])
但是,每次我运行此命令时,结果仍在[1,3]
中,而不是[3,1]
中。我想知道我反向做错了什么。
解决方法
您遇到了一些问题:
- 错误的
end
值,它应该是length - 1
的最后一个索引, - 当检查错误时,您需要检查
start < end
,原始代码在开始false
处,这就是获取不变数组的原因, - 缺少
start
的增量和end
的减量。
function reverseInPlace(arr) {
let start = 0,end = arr.length - 1;
while (start < end) {
let temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
return arr;
}
console.log(reverseInPlace([1,2,3]));
,
看起来您的while循环永远不会执行。由于您已启动var,因此start = 0,end = arr.length。在while循环中,开始和结束也应同时更新。
function reverseInPlace(arr) {
var start = 0;
var end = arr.length-1;
while (start < end) {
var temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
end--;
start++;
}
return arr;
};
console.log(reverseInPlace([1,3]))
,
首先,start
小于end
,while (start > end)
循环将永远不会运行,您还需要更新start
和end
来交换下一对数字:
function reverseInPlace(arr) {
var start = 0;
var end = arr.length - 1;
while (start < end) {
var temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
return arr;
};
var res = reverseInPlace([1,3])
console.log(res);
,
有一种简单的方法可以使用pop和push js函数
public class Client
{
HttpClient _httpClient;
public Client()
{
_httpClient=new HttpClient();
}
//async post,get request
public async Task<string> sendGetRequest(string url)
{
var response= await _httpClient.GetAsync(url);
if(response.IsSuccessStatusCode)
{
//if response has status code 200 do something
//in this case I'm just converting the content of the response in string format
string result=await response.Content.ReadStringAsync();
}
else
{
return "error";
}
}
public async Task<string> sendPostRequest(string url,string bodyJson)
{
//Example sending a post request with json as body.
var body=new StringContent(bodyJson,Encoding.UTF8,"application/json");
var response= await _httpClient.PostAsync(url,body);
if(response.IsSuccessStatusCode)
{
//if response has status code 200 do something
//in this case I'm just converting the contntent of the response in string format
string result=await response.Content.ReadStringAsync();
return result;
}
else
{
return "error";
}
}
}