leetcode编程题(4)

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

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值