前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2021-09-03:直线上最多的点数。给你一个数组 points ,其

2021-09-03:直线上最多的点数。给你一个数组 points ,其

原创
作者头像
福大大架构师每日一题
修改2021-09-04 09:21:38
2120
修改2021-09-04 09:21:38
举报

2021-09-03:直线上最多的点数。给你一个数组 points ,其中 pointsi = xi, yi 表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。力扣149。

福大大 答案2021-09-03:

具体见代码。

代码用golang编写。代码如下:

代码语言:txt
复制
package main

import "fmt"

func main() {
    //points := [][]int{{1, 1}, {2, 2}, {3, 3}}
    points := [][]int{{1, 1}, {3, 2}, {5, 3}, {4, 1}, {2, 3}, {1, 4}}
    ret := maxPoints(points)
    fmt.Println(ret)
}

// [
//    [1,3]
//    [4,9]
//    [5,7]
//   ]

func maxPoints(points [][]int) int {
    if points == nil {
        return 0
    }
    if len(points) <= 2 {
        return len(points)
    }
    // key = 3
    // value = {7 , 10}  -> 斜率为3/7的点 有10个
    //         {5,  15}  -> 斜率为3/5的点 有15个
    map0 := make(map[int]map[int]int)
    result := 0
    for i := 0; i < len(points); i++ {
        map0 = make(map[int]map[int]int)
        samePosition := 1
        sameX := 0
        sameY := 0
        line := 0
        for j := i + 1; j < len(points); j++ { // i号点,和j号点,的斜率关系
            x := points[j][0] - points[i][0]
            y := points[j][1] - points[i][1]
            if x == 0 && y == 0 {
                samePosition++
            } else if x == 0 {
                sameX++
            } else if y == 0 {
                sameY++
            } else { // 普通斜率
                gcd0 := gcd(x, y)
                x /= gcd0
                y /= gcd0
                // x / y
                if _, ok := map0[x]; !ok {
                    map0[x] = make(map[int]int)
                }
                if _, ok := map0[x][y]; !ok {
                    map0[x][y] = 0
                }
                map0[x][y] = map0[x][y] + 1
                line = getMax(line, map0[x][y])
            }
        }
        result = getMax(result, getMax(getMax(sameX, sameY), line)+samePosition)
    }
    return result
}

// 保证初始调用的时候,a和b不等于0
// O(1)
func gcd(a int, b int) int {
    if b == 0 {
        return a
    } else {
        return gcd(b, a%b)
    }
}

func getMax(a int, b int) int {
    if a > b {
        return a
    } else {
        return b
    }
}

执行结果如下:

图片
图片

左神java代码

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档