Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Find Closest Number to Zero #19

Open
@Revamth

Description

#include <vector>
#include <cmath>
#include <algorithm>
class Solution {
public:
 int findClosestNumber(const std::vector<int>& nums) {
 int closest = nums[0];
 
 for (int x : nums) {
 if (std::abs(x) < std::abs(closest)) {
 closest = x;
 }
 }
 
 if (closest < 0 && std::find(nums.begin(), nums.end(), std::abs(closest)) != nums.end()) {
 return std::abs(closest);
 } else {
 return closest;
 }
 }
};

The solution which you have provided has a time complexity of O(2n) in the worst case.

Instead of using the std::find function call we can simply keep track whether the minimum value we are getting is coming from negative value and positive value and update answer accordingly.

My code is provided here. Please verify it:

class Solution
{
 public:
 int findClosestNumber(vector<int> &nums)
 {
 int n = nums.size();
 int ans = INT_MAX;
 bool val = false;
 for (int i = 0; i < n; i++)
 {
 if (nums[i] > 0)
 {
 if (nums[i] <= ans)
 {
 ans = nums[i];
 val = true;
 }
 }
 else
 {
 int num = -nums[i];
 if (num < ans)
 {
 ans = num;
 val = false;
 }
 }
 }
 if (val == false) return -ans;
 else return ans;
 }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

        AltStyle によって変換されたページ (->オリジナル) /