1221. 分割平衡字符串](https://leetcode.cn/problems/split-a-string-in-balanced-strings/)
class Solution {
public int balancedStringSplit(String s) {
int statisNum=0;
int finalNum=0;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c == 'L'){
statisNum++;
}else if(c == 'R'){
statisNum--;
}
if(statisNum==0){-
finalNum++;
}
}
return finalNum;
}
}
1217. 玩筹码
数组的数据量比较小,枚举每种情况,计算他的成本,移到奇数为成本为1,然后每次计算完,取最小值,遍历结束即可得出最小值
class Solution {
public int minCostToMoveChips(int[] position) {
int cost,minCost= 1000000000;
for(int i=0;i<position.length;++i){
cost = 0;
for(int j=0;j<position.length;++j){
if(((position[j]-position[i])&1) == 1){
++cost;
}
}
minCost = Math.min(minCost,cost);
}
return minCost;
}
}
1029. 两地调度
class Solution {
public List<List<Integer>> arrToList(int[][] costs){
List<List<Integer>> arrToList = new ArrayList<>();
for (int i = 0; i < costs.length; i++) {
List<Integer> arr = new ArrayList<>();
for (int j = 0; j < costs[i].length; j++) {
arr.add(costs[i][j]);
}
arrToList.add(arr);
}
return arrToList;
}
public int twoCitySchedCost(int[][] costs) {
List<List<Integer>> lists = arrToList(costs);
lists.sort((a,b)->{
return (a.get(0) - a.get(1)) - (b.get(0)-b.get(1));
});
int n = costs.length /2;
int i;
int ret = 0;
for (i= 0; i < n; i++){
ret+=lists.get(i).get(0)+lists.get(i+n).get(1);
}
return ret;
}
}
面试题 10.11. 峰与谷
先从小到大升序排序,然后通过两个指针,交替从两头开始遍历nums数组,此时出现的效果就是,先放小的再放大的,大小交替放置 就呈现出了 波峰波谷交替出现
class Solution {
public void wiggleSort(int[] nums) {
Arrays.sort(nums);
List<Integer> tmp = new ArrayList<Integer>();
int l = 0, r = nums.length - 1;
while (l < r) {
tmp.add(nums[r--]);
tmp.add(nums[l++]);
}
if(l==r){
tmp.add(nums[l]);
}
for (int i = 0; i < nums.length; i++) {
nums[i] = tmp.get(i);
}
}
}