https://leetcode-cn.com/problems/di-string-match
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* diStringMatch(char * S, int* returnSize){
int left = 0;
int right = strlen(S);
int len = strlen(S);
int *A = malloc(sizeof(int) * (strlen(S) + 1)); // 谨记malloc 语法
int i = 0;
int j = 0;
for(j = 0; j < len; j++){
if(S[j] == 'I') {
A[i++] = left++;
} else {
A[i++] = right--;
}
}
A[i++] = right;//思考这里:为什么单独如此一句呢?
*returnSize = i;
return A;
}
执行用时 :
88 ms
, 在所有 C 提交中击败了
9.36%
的用户
内存消耗 :
12.9 MB
, 在所有 C 提交中击败了
44.53%
的用户
class Solution:
def diStringMatch(self, S: str) -> List[int]:
left = 0
right = len(S)
ans = []
for i in S:
if i == 'I':
ans.append(left)
left += 1
else:
ans.append(right)
right -= 1
ans.append(right)
return ans
'''
执行用时 :
68 ms
, 在所有 Python3 提交中击败了
79.74%
的用户
内存消耗 :
14.2 MB
, 在所有 Python3 提交中击败了
52.81%
的用户
'''
https://leetcode-cn.com/problems/squares-of-a-sorted-array
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
return sorted([i**2 for i in A])
'''
# for sort: you have:
list.sort(cmp=None, key=None, reverse=False)
# for sorted: you have:
sorted()方法,返回一个新的list; ################# 学习点!!!!
# summary:
如果你不需要保留原来的list, 使用list.sort()方法来排序,此时list本身将被修改。通常此方法不如sorted()方便
'''
执行用时 :
312 ms
, 在所有 Python3 提交中击败了
35.49%
的用户
内存消耗 :
15 MB
, 在所有 Python3 提交中击败了
59.04%
的用户
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortedSquares(int* A, int ASize, int* returnSize){
int i = 0, j = ASize - 1;
int k = ASize - 1;
int *ans = (int *)malloc(sizeof(int) * ASize);
while(i <= j) {
if (abs(A[i]) > abs(A[j])) {
ans[k] = A[i] * A[i];
k--;
i++;
} else {
ans[k] = A[j] * A[j];
k--;
j--;
}
}
*returnSize = ASize;
return ans;
}
执行用时 :
132 ms
, 在所有 C 提交中击败了
82.21%
的用户
内存消耗 :
21.5 MB
, 在所有 C 提交中击败了
41.91%
的用户
原文:https://www.cnblogs.com/paulkg12/p/12268206.html