Skip to content

Add solution 0977 solution.js #149

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
merged 1 commit into from
Feb 8, 2019
Merged
Changes from all commits
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
44 changes: 44 additions & 0 deletions solution/0977.Squares of a Sorted Array/Solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* @param {number[]} A
* @return {number[]}
*/

// 第一种解法
var sortedSquares = function(A) {
let results = A.map((item, index, array) => {
return item *= item;
});
results.sort((v1, v2) => {
return v1 -v2;
});
return results;
};
// 第二种解法
var sortedSquares = function(A){
let len = A.length; // 数组长度
let j = 0; // j 正数开始
while(j < len && A[j] < 0){
j++;
};
let i = j - 1; // i 负数开始
let results = []; // 存放最终结果
let t = 0; // results下标
while(i >= 0 && j < len){
if (A[i] * A[i] < A[j] * A[j]) {
results[t++] = A[i] * A[i];
i--;
} else {
results[t++] = A[j] * A[j];
j++;
}
}
while(i >= 0){
results[t++] = A[i] * A[i];
i--;
}
while(j < len){
results[t++] = A[j] * A[j];
j++;
}
return results;
}