Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from youngyangyang04:master #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 6 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Sep 2, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
0977.有序数组的平方-typescript版本-优化写法
  • Loading branch information
hua-qi committed Aug 30, 2022
commit d91233d0443753b747d139e00b081fa4f4c39fb1
22 changes: 14 additions & 8 deletions problems/0977.有序数组的平方.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -239,18 +239,24 @@ Typescript:

```typescript
function sortedSquares(nums: number[]): number[] {
let left: number = 0, right: number = nums.length - 1;
let resArr: number[] = new Array(nums.length);
let resArrIndex: number = resArr.length - 1;
const ans: number[] = [];
let left = 0,
right = nums.length - 1;

while (left <= right) {
if (Math.abs(nums[left]) < Math.abs(nums[right])) {
resArr[resArrIndex] = nums[right--] ** 2;
// 右侧的元素不需要取绝对值,nums 为非递减排序的整数数组
// 在同为负数的情况下,左侧的平方值一定大于右侧的平方值
if (Math.abs(nums[left]) > nums[right]) {
// 使用 Array.prototype.unshift() 直接在数组的首项插入当前最大值
ans.unshift(nums[left] ** 2);
left++;
} else {
resArr[resArrIndex] = nums[left++] ** 2;
ans.unshift(nums[right] ** 2);
right--;
}
resArrIndex--;
}
return resArr;

return ans;
};
```

Expand Down

AltStyle によって変換されたページ (->オリジナル) /