版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
时间: 2019-10-22 11:56 PM
题目地址: https://leetcode.com/problems/sort-an-array/
Given an array of integers nums, sort the array in ascending order.
给定一个整型数组,升序排序。
Example 1:
Input: [5,2,3,1]
Output: [1,2,3,5]
Example 1:
Input: [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Solution (INSERTION-SORT):
public int[] sortArray(int[] nums) {
if (null == nums || nums.length <= 1) {
return nums;
}
for (int j = 1; j < nums.length; ++j) {
int key = nums[j];
int i = j - 1;
while (i >= 0 && nums[i] > key) {
nums[i + 1] = nums[i];
--i;
}
nums[i + 1] = key;
}
return nums;
}
Runtime: 239 ms, faster than 8.89% of Java online submissions for Sort an Array.
Memory Usage: 41.1 MB, less than 100.00% of Java online submissions for Sort an Array.