561. 数组拆分 I
原文链接:https://leetcode-cn.com/problems/array-partition-i/
思路分析:进行升序排序后者写一对对的数是就现在的数组元素,每对最小数相加就是数组偶数位元素相加
代码:
class Solution {
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int sum = 0;
for(int i = 0;i<nums.length;i+=2) {
sum = sum+nums[i];
}
return sum;
}
}
977. 有序数组的平方
原文链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array/
思路分析:对数组每个元素计算平方值,后对数组进行排序。
代码:
class Solution {
public int[] sortedSquares(int[] A) {
int[] sum = new int[A.length];
for (int i = 0; i < A.length; ++i){
sum[i] = A[i] * A[i];
}
Arrays.sort(sum);
return sum;
}
}
1051. 高度检查器
原文链接:https://leetcode-cn.com/problems/height-checker/
思路分析:通过计数排序的思想进行排序
代码:
class Solution {
public int heightChecker(int[] heights) {
int[] arr = new int[101];
for (int height : heights) {
arr[height]++;
}
int count = 0;
for (int i = 1, j = 0; i < arr.length; i++) {
while (arr[i]-- > 0) {
if (heights[j++] != i)
count++;
}
}
return count;
}
}
面试题 01.02. 判定是否互为字符重排
原文链接:https://leetcode-cn.com/problems/check-permutation-lcci/
思路分析:先判断两个数组长度是否一样,在对两个数组进行判断。
代码:
class Solution {
public boolean CheckPermutation(String s1, String s2) {
if (s1.length()!=s2.length())
return false;
int[] temp=new int[256];
for (int i = 0; i <s1.length() ; i++) {
char c = s1.charAt(i);
temp[c]++;
}
for (int i = 0; i <s2.length() ; i++) {
char c=s2.charAt(i);
if (temp[c]==0) {
return false;
}
else
temp[c]--;
}
return true;
}
}