1365. 有多少小于当前数字的数字
原文链接:https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number/
思路分析:将数组中的每个元素于其它元素对比下统计其小于这个元素的个数
代码:
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int [] sum=new int[nums.length];
for(int i=0;i<nums.length;i++){
int count=0;
for(int j=0;j<nums.length;j++){
if(nums[i]>nums[j]){
count ++;
}
}
sum[i]=count;
}
return sum;
}
}
1299. 将每个元素替换为右侧最大元素
原文链接:https://leetcode-cn.com/problems/replace-elements-with-greatest-element-on-right-side/
思路分析:从右往左遍历,先记录右边最大值 rightMax 为最后一个值,向左每次更新 rightMax,使用变量 t 先记住当前 arr[i] 就可以了。
代码:
class Solution {
public int[] replaceElements(int[] arr) {
int rightMax = arr[arr.length - 1];
arr[arr.length - 1] = -1;
for (int i = arr.length - 2; i >= 0; i--) {
int t = arr[i];
arr[i] = rightMax;
if (t > rightMax)
rightMax = t;
}
return arr;
}
}
832. 翻转图像
原文链接:https://leetcode-cn.com/problems/flipping-an-image/
思路分析:定义两个指针,遍历每一行;左指针从左向右,右指针从右向左遍历;数字不同继续遍历,数字相同则将0换程1,1换成0;当指针指向同一位置,说明行元素为奇数个,此时将0换成1,1换成0;
代码:
class Solution {
public int[][] flipAndInvertImage(int[][] A) {
for (int i = 0; i < A.length; i++) {
int left = 0;
int right = A[i].length - 1;
while (left < right) {
if (A[i][left] != A[i][right]) {
left++;
right--;
} else {
A[i][left] = A[i][left] == 1 ? 0 : 1;
A[i][right] = A[i][right] == 1 ? 0 : 1;
left++;
right--;
}
}
if (left == right) {
A[i][left] = A[i][left] == 1 ? 0 : 1;
}
}
return A;
}
}
面试题01.01.判断字符是否唯一
原文链接:https://leetcode-cn.com/problems/is-unique-lcci/
思路分析:直接将字符串中的字符比较,有相同的返回false
代码:
class Solution {
public boolean isUnique(String astr) {
boolean sum = true;
for(int i = 0; i < astr.length() - 1; i++){
for(int j = i + 1; j < astr.length(); j++){
if(astr.charAt(i) == astr.charAt(j)){
return false;
}
}
}
return sum;
}
}