977. Squares of a Sorted Array
題目:
Given an integer array nums
sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100].
Example 2:
Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121]
Constraints:
1 <= nums.length <= 10^4
-104 <= nums[i] <= 10^4
nums
is sorted in non-decreasing order.
思路:
這題資料量較小,只有10的4次方,因此直接在原陣列上進行平方然後再sort也可以通過。這裡說一個雙指標one pass的方法。先建立大小相等的空陣列來記錄答案,然後左右指標分別指向原陣列兩端,誰的絕對值/平方大就選誰,從空陣列的後面開始放,一路向前即可。
程式碼:
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int n=nums.size();
vector<int> res(n);
int l=0, r=n-1;
for(int i=n-1;i>=0;i--)
{
if(abs(nums[l])>abs(nums[r]))
{
res[i]=nums[l]*nums[l];
l++;
}
else
{
res[i]=nums[r]*nums[r];
r--;
}
}
return res;
}
};
相關文章
- LeetCode之Squares of a Sorted Array(Kotlin)LeetCodeKotlin
- # Search in Rotated Sorted Array
- 88. Merge Sorted Array
- Leetcode 88. Merge Sorted ArrayLeetCode
- Leetcode 33 Search in Rotated Sorted ArrayLeetCode
- 【刷題】Search in a Big Sorted Array
- Remove-duplicates-from-sorted-arrayREM
- [LeetCode] 3011. Find if Array Can Be SortedLeetCode
- Find Minimum in Rotated Sorted Array I & II
- Leetcode 26 Remove Duplicates from Sorted ArrayLeetCodeREM
- LeetCode | 153. Find Minimum in Rotated Sorted ArrayLeetCode
- [leetcode]convert-sorted-array-to-binary-search-treeLeetCode
- [leetcode]remove-duplicates-from-sorted-array-iiLeetCodeREM
- [LeetCode] 702. Search in a Sorted Array of Unknown SizeLeetCode
- 108-Convert Sorted Array to Binary Search Tree
- [LeetCode] 80. Remove Duplicates from Sorted Array IILeetCodeREM
- Leetcode 34 Find First and Last Position of Element in Sorted ArrayLeetCodeAST
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- LeetCode C++ 33. Search in Rotated Sorted Array【二分】中等LeetCodeC++
- Leetcode Perfect SquaresLeetCode
- [LeetCode] 425. Word SquaresLeetCode
- [LeetCode] 279. Perfect SquaresLeetCode
- 【leetcode】26. Remove Duplicates from Sorted Array 刪除有序陣列的重複元素LeetCodeREM陣列
- cf314E. Sereja and Squares(dp)
- AtCoder ARC097C Sorted and Sorted:dp
- python sorted keyPython
- 977. 有序陣列的平方陣列
- Merge Two Sorted List
- Array.from和 Array.of
- HDH 1264 Counting Squares (線段樹+掃描線|暴力)
- array
- PHP用foreach來表達array_walk/array_filter/array_map/array_reducePHPFilter
- 【陣列】977. 有序陣列的平方陣列
- Array()與Array.of()方法區別
- JS Array.reduce 實現 Array.map 和 Array.filterJSFilter
- array_filter ()、array_map ()、array_walk () 區別?容易記混淆!!!Filter
- Unique Array
- Array Division