added productExceprSelf
This commit is contained in:
@@ -16,3 +16,4 @@ add_subdirectory(canJump)
|
||||
add_subdirectory(jump)
|
||||
add_subdirectory(hindex)
|
||||
add_subdirectory(randomizedset)
|
||||
add_subdirectory(productExceptSelf)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
SUBDIRS := canJump jump majorityelement maxprofit maxprofit2 rmdupfromsortedarray rmdupfromsortedarray2 rotate twopointers hindex randomizedset
|
||||
SUBDIRS := canJump jump majorityelement maxprofit maxprofit2 rmdupfromsortedarray rmdupfromsortedarray2 rotate twopointers hindex randomizedset productExceptSelf
|
||||
|
||||
all: $(SUBDIRS)
|
||||
|
||||
|
||||
@@ -10,3 +10,4 @@ subdir('canJump')
|
||||
subdir('jump')
|
||||
subdir('hindex')
|
||||
subdir('randomizedset')
|
||||
subdir('productExceptSelf')
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
FILE(GLOB_RECURSE SOURCES src/*.cpp)
|
||||
|
||||
add_executable(
|
||||
productExceptSelf
|
||||
${SOURCES}
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
CXX = g++
|
||||
CFLAGS = -Wall -g
|
||||
SRCS = $(wildcard src/*/*.cpp src/*.cpp)
|
||||
OBJS = $(SRCS:.cpp=.o)
|
||||
TARGET = productExceptSelf
|
||||
CROSS_COMPILE =
|
||||
|
||||
all: $(TARGET)
|
||||
|
||||
$(TARGET): $(OBJS)
|
||||
$(CROSS_COMPILE)$(CXX) $(LDFLAGS) $^ -o $@ $(LIBS)
|
||||
|
||||
%.o: %.cpp
|
||||
$(CROSS_COMPILE)$(CXX) $(CFLAGS) $(INCLUDES) -c $< -o $@
|
||||
|
||||
clean:
|
||||
rm -f $(OBJS) $(TARGET)
|
||||
@@ -0,0 +1 @@
|
||||
executable('productExceptSelf', 'src/main.cpp', install: true)
|
||||
@@ -0,0 +1,16 @@
|
||||
#include <cassert>
|
||||
#include <vector>
|
||||
#include "productExceptSelf.hpp"
|
||||
|
||||
int main() {
|
||||
std::vector<int> nums = {1, 2, 3, 4};
|
||||
std::vector<int> expectednums = {24, 12, 8, 6};
|
||||
std::vector<int> resnums = productExceptSelf(nums);
|
||||
assert(resnums == expectednums);
|
||||
|
||||
nums = {-1, 1, 0, -3, 3};
|
||||
expectednums = {0, 0, 9, 0, 0};
|
||||
resnums = productExceptSelf(nums);
|
||||
assert(resnums == expectednums);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#include <vector>
|
||||
|
||||
inline std::vector<int> productExceptSelf(std::vector<int> &nums) {
|
||||
int n = nums.size();
|
||||
}
|
||||
|
||||
// def productExceptSelf(nums):
|
||||
// n = len(nums)
|
||||
// answer = [1] * n
|
||||
|
||||
// #Первый проход : префиксные произведения
|
||||
// #answer[i] содержит произведение всех элементов слева от i
|
||||
// for i in range(1, n):
|
||||
// answer[i] = answer[i-1] * nums[i-1]
|
||||
|
||||
// #Второй проход : суффиксные произведения
|
||||
// #suffix накапливает произведение элементов справа
|
||||
// suffix = 1
|
||||
// for i in range(n-1, -1, -1):
|
||||
// answer[i] *= suffix # умножаем на произведение справа
|
||||
// suffix *= nums[i] # обновляем суффиксное произведение
|
||||
|
||||
// return answer
|
||||
Reference in New Issue
Block a user