【英雄算法联盟】6月集训Day4.贪心

本文介绍了四道Java面试中关于字符串分割、筹码移动策略、成本最小调度和数组排序的典型问题。通过实例展示了如何利用计数法解决字符串平衡,使用数学原理优化筹码移动,以及运用排序和选择算法降低调度成本。这些技巧是理解算法设计和优化的基础。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目1:1221. 分割平衡字符串

当能凑齐一对L和R的时候就直接结果+1

class Solution {
    public int balancedStringSplit(String s) {
        int ans = 0;
        int cnt = 0;
        for (int i = 0; i < s.length(); i++) {
            char ss = s.charAt(i);
            if (ss == 'L') {
                cnt++;
            } else if (ss == 'R') {
                cnt--;
            }
            if (cnt == 0) {
                ans++;
            }
        }
        return ans;
    }
}

题目2:1217. 玩筹码

从题目给的例子分析得到:偶数位置到偶数位置、奇数位置到奇数位置都没有代价;如果性质不同则代价为1;所以统计所有的奇数、偶数数量,取最小的即为代价,另一边直接代价为0。

class Solution {
    public int minCostToMoveChips(int[] position) {
        int oddCount = 0, evenCount = 0;
        for (int num: position) {
            if (num%2 == 0) {
                evenCount++;
            } else {
                oddCount++;
            }
        }
        return Math.min(oddCount,evenCount);
    }
}

题目3:两地调度

对于第i位同志,派往A地的成本是【A价格-B价格】,按照成本对costs数组进行排序,选取前N位同志去A,后面的去B就是实现了成本最低。

class Solution {
    public int twoCitySchedCost(int[][] costs) {
    Arrays.sort(costs, (a,b) -> a[0]-a[1]-(b[0]-b[1]));
      int total = 0;
      int n = costs.length / 2;
      for (int i = 0; i < n; ++i) {
          total += costs[i][0] + costs[i + n][1];
      }
      return total;
    }
}

题目4:面试题 10.11. 峰与谷

先对原数组进行排序,然后根据题意,调整数组数值。

class Solution {
    public void wiggleSort(int[] nums) {
        Arrays.sort(nums);
        for(int i=0;i<nums.length-1;i+=2){
            int temp=nums[i];
            nums[i] = nums[i+1];
            nums[i+1] = temp;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值