Leetcode -- Day 20 & Day 21

Binary search in sorted Array

Question 1

Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Refer to this link below:

http://www.cnblogs.com/springfor/p/3861890.html

 1 public class Solution {
 2     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
 3         if (nums1 == null || nums2 == null)
 4             return 0;
 5         int m = nums1.length;
 6         int n = nums2.length;
 7         int k = (m+n)/2;
 8
 9         if ((m+n) % 2 == 0){
10             double first = findMedianSortedArrays(nums1,0,m-1,nums2,0,n-1,k);
11             double second = findMedianSortedArrays(nums1,0,m-1,nums2,0,n-1,k+1);
12             return (first+second)/2;
13         }
14         else
15             return findMedianSortedArrays(nums1,0,m-1,nums2,0,n-1,k+1);
16     }
17
18     public double findMedianSortedArrays(int[] A, int sA, int eA, int[] B, int sB, int eB, int k){
19         int m = eA - sA + 1;
20         int n = eB - sB + 1;
21         if (m > n)
22             return findMedianSortedArrays(B, sB, eB, A, sA, eA, k);
23         if (m == 0)
24             return B[k-1];
25         if (k == 1)
26             return Math.min(A[sA], B[sB]);
27         int partA = Math.min(k/2, m);
28         int partB = k - partA;
29         if (A[sA + partA-1] < B[sB + partB - 1])
30             return findMedianSortedArrays(A, sA + partA, eA, B, sB, eB, k-partA);
31         else if (A[sA + partA-1] > B[sB + partB - 1])
32             return findMedianSortedArrays(A, sA, eA, B, sB+partB, eB, k-partB);
33         else
34             return A[sA + partA - 1];
35     }
36 }

Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

row and colum‘s product -1 is the total number of this values. And a trick here is mid/colum is the row and mid%colum is the column.

public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length < 1)
            return false;

        int left = 0;
        int right = matrix.length * matrix[0].length - 1;

        while (left <= right){
            int mid = (left + right)/2;
            int value = matrix[mid/matrix[0].length][mid % matrix[0].length];
            if (value == target){
                return true;
            }
            else if (value < target){
                left = mid + 1;
            }
            else {
                right = mid - 1;
            }
        }
        return false;
    }

This is my initial solution, using two loops, more complex but more directly.

 1 public boolean searchMatrix(int[][] matrix, int target) {
 2         if (matrix == null)
 3             return false;
 4
 5         if (matrix[0][0] > target)
 6             return false;
 7         int row_mid;
 8         int col_mid;
 9         int row_start = 0;
10         int col_start = 0;
11         int row_end = matrix.length-1;
12         int col_end = matrix[0].length-1;
13
14         while (row_start <= row_end){
15             row_mid = (row_start + row_end)/2;
16             // matrix[row_mid][] is the one we are interested in
17             if (matrix[row_mid][0] == target){
18                 return true;
19             }
20             else if (matrix[row_mid][0] > target){
21                 row_end = row_mid - 1;
22             }
23             else {
24                 row_start = row_mid + 1;
25             }
26         }
27
28         row_mid = row_end;
29         if (row_mid < 0)
30             return false;
31
32         while (col_start <= col_end){
33             col_mid = (col_start + col_end)/2;
34             int value = matrix[row_mid][col_mid];
35             if (value == target){
36                 return true;
37             }
38             else if (value < target){
39                 col_start = col_mid + 1;
40             }
41             else{
42                 col_end = col_mid - 1;
43             }
44         }
45
46         return false;
47     }
时间: 2024-11-05 21:55:47

Leetcode -- Day 20 & Day 21的相关文章

[LeetCode] Search Insert Position [21]

题目 Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6]

String转jsonarry:字符串:[{&quot;result&quot;:&quot;20&quot;},{&quot;result&quot;:&quot;21&quot;},{&quot;result&quot;:&quot;20&quot;},{&quot;result&quot;:&quot;22&quot;}]

List<HashMap<String, Object>> grididmap = new ArrayList<HashMap<String,Object>>(); String a = bs.toString();   //bs的字符串为如下形式:[{"result":"20"},{"result":"21"},{"result":"20"

FTP的20、21端口,工作模式

什么是FTP? FTP就是文件传输协议 File Transfer Protocol 的缩写. FTP端口号是多少? 21 FTP的端口号能改吗? 能 ftp的端口号20.21有何区别? 一个是数据端口,一个是控制端口,控制端口一般为21,而数据端口不一定是20,这和FTP的应用模式有关,如果是主动模式,应该为20,如果为被动模式,由服务器端和客户端协商而定 FTP Port模式和FTP Passive模式 当你对一个FTP问题进行排错时候,你首先要问的一个问题是使用的是port模式的还是pas

2016年5月20日~21日,杨学明老师为北京某著名上市企业提供内训课程服务!

2016年5月20日~21日,在北京市中关村软件园,杨学明老师为北京某著名上市企业提供内训课程服务!20日上午9点,人力资源部曹经理宣布课程准时开始,在大家一片掌声中,杨学明老师开始了为期了两天的<软件测试需求分析与测试用例设计>的课程.杨学明老师分别从软件测试的概论.软件测试需求分析.软件测试设计的五个维度.基于质量属性的测试设计.测试缺陷分析与度量.课程总结等几个维度讲述了软件测试设计的内容.课程中有电影,FLASH,研讨和问答等环节,并且安插了许多游戏环节,整个课程十分丰富而多彩,学员普

JavaScript高级程序设计(第三版)学习笔记20、21、23章

第20章,JSON JSON(JavaScript Object Notation,JavaScript对象表示法),是JavaScript的一个严格的子集. JSON可表示一下三种类型值: 简单值:字符串,数值,布尔值,null,不支持js特殊值:undefined 对象:一组无序的键值对 数组:一组有序的值的列表 不支持变量,函数或对象实例 注:JSON的字符串必须使用双引号,这是与JavaScript字符串最大的区别 对象 { "name":"Nicholas"

[Leetcode][Python]20: Valid Parentheses

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 20: Valid Parentheseshttps://oj.leetcode.com/problems/valid-parentheses/ Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.T

NYOJ 搜索题目汇总 NYOJ 20、21、27、42、58、82、202、284、325、353、488、491、523、592、722

NYOJ 搜索题目汇总 NYOJ 20 #include<iostream> #include<cstdio> #include<cstring> #include<string> #include<vector> #include<algorithm> using namespace std; int pre[100005]; vector<int>v[100005];//存储每个结点相邻的边 void DFS(int

EC读书笔记系列之11:条款20、21

条款20 宁以pass-by-reference-to-const替换pass-by-value 记住: ★尽量以pass-by-reference-to-const替换pass-by-value.前者通常高效,并可避免切割问题 ★以上规则并不适用于内置类型,以及STL的迭代器和函数对象.那些应用pass-by-value 条款21 必须返回对象时,别妄想返回其reference 记住: ★绝不要返回pointer或reference指向一个local stack对象(如函数里的局部对象):或返

《MORE EFFECTIVE C++》条款20 条款21

条款20 协助编译器实现返回值优化 当重载运算符的时候,比如+ - * / 这类运算符,该函数返回的值一定是个右值(即不能是引用),那么执行一次运算的开销可能会在临时对象上调用多次构造函数和析构函数,这笔开销还是很大的.现在的新编译器已经可以对这种情况进行优化了,甚至优化到连开销都没有,只是有一定的适用范围.如果可以返回一个匿名的临时对象,并且利用构造函数来得到结果对象,那么就有可能被优化到零开销.注意,有名字的对象意味着返回值优化不可用. 假设有如下的代码: 1 node a(2); 2 no