牛客网:NC86 矩阵元素查找

这篇博客探讨了三种不同的算法在二维矩阵中查找特定元素的方法。首先介绍了暴力遍历的方法,遍历矩阵的所有元素以找到目标值。接着,展示了贪心策略,通过从右下角开始移动来提高效率。最后,利用二分查找的思想,优化了在有序矩阵列中的搜索过程。这些算法各有优缺点,适用于不同的场景。
摘要由CSDN通过智能技术生成

暴力

import java.util.*;

public class Solution {
    public int[] findElement(int[][] mat, int n, int m, int x) {
        // write code here
        for(int i = 0; i < n; i++){
            for (int j = 0; j < m; j++){
                if (mat[i][j] == x){
                    return new int[]{i , j};
                }
            }
        }
        return null;
    }
}

使用贪心

import java.util.*;

public class Solution {
    public int[] findElement(int[][] mat, int n, int m, int x) {
        // write code here
        int i = n - 1, j = 0;
        while (i >= 0 && j < m){
            if (mat[i][j] == x) break;
            if (mat[i][j] > x) i--;
            else j++;
        }
        return new int[]{i, j};
    }
}

使用二分

import java.util.*;

public class Solution {
    public int[] findElement(int[][] mat, int n, int m, int x) {
        // write code here
        for (int i = 0; i < n; i++){
            if (mat[i][m - 1] < x) continue;
            int left = 0, right = m - 1;
            while (left <= right){
                int mid = (left + right) >> 1;
                if (mat[i][mid] == x) return new int[]{i , mid};
                if (mat[i][mid] < x) left = mid + 1;
                else right = mid - 1;
            }
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值