leetcode编程题(5)

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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值