您的位置:首页 > 其它

leetcode977.有序数组的平方

2019-05-06 15:37 477 查看

leetcode977.有序数组的平方

代码

python2.7

class Solution(object):
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
return sorted( [i*i for i in A] )

C++

class Solution {
public:
int abs(int x){
return (x>=0)?x:(-x);
}

vector<int> sortedSquares(vector<int>& A) {
vector<int> ans(A.size());
int i=0, j=A.size()-1;
int index = j;
while (index>=0){
if (abs(A[i]) >= abs(A[j]) ){
ans[index] = A[i]*A[i];
i++;
index--;
}
else {
ans[index] = A[j]*A[j];
j--;
index--;
}
}
return ans;
}
};

总结

  • python中array.sort()无return值,sorted(array)有return值,都是对array排序;
  • C++STL中vector用法!见CSDN/C++/vector
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: